Silverlight 绑定数据时修改数据 数据转换

我们经常有这样的需求,给xaml的一个元素绑定一个值,但是显示用绑定值来显示其他的值。比如从数据库中取出的日期是2010-11-14,显示的时候需要显示2010年11月14日,怎么解决这个需求呢?silverlight给我们提供了一个IValueConverter接口来解决这个问题。

该接口有两个方法:

Convert:在将源数据传递到目标以在 UI 中显示之前,对源数据进行修改。

ConvertBack:在将目标数据传递到源对象之前,对目标数据进行修改。此方法仅在 TwoWay 绑定中进行调用。

  

我们接下来来实现一个日期的例子:

 

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null || value.ToString() == "") return "";
            string param = parameter as string;
            if (param == "A")
            {
                try
                { return DateTime.Parse(value.ToString()).ToString("yyyy年MM月dd日"); }
                catch
                { throw; }
            }
            else
            {
                try
                { return DateTime.Parse(value.ToString()).ToLongTimeString(); }
                catch
                { throw; }
            }
        }

这个方法用到了要在转换器逻辑中使用的可选参数进行日期的转换。

xaml代码比较简单直接贴出来:

<Grid x:Name="LayoutRoot" Background="White">
        <sdk:DatePicker Height="23" HorizontalAlignment="Left" Margin="88,52,0,0" Name="datePicker1" VerticalAlignment="Top" Width="120" />
        <TextBlock Height="53" HorizontalAlignment="Left" Margin="88,95,0,0" Name="textBlock1" Text="{Binding ElementName=datePicker1, Path=Text,Converter={StaticResource converter}, ConverterParameter=A}" VerticalAlignment="Top" Width="142" />
        <TextBlock Height="58" HorizontalAlignment="Left" Margin="88,154,0,0" Name="textBlock2" Text="{Binding ElementName=datePicker1,Path=Text,Converter={StaticResource converter}, ConverterParameter=B}" VerticalAlignment="Top" Width="142" />
    </Grid>

 

 运行结果:

 

代码比较简单,不再赘述,有兴趣的同学可以下载参考:https://files.cnblogs.com/Clivia/SilverlightConverter.rar

 

silverlight4对绑定提供了更多的支持,通过StringFormat可以指定绑定数据的显示格式处理代替上面简单示例中对日期的转换,从而不用实现IValueConverter借口,这个只能处理简单的转换,复杂类型的转换还需要实现IValueConverter接口。下面给出StringFormat的使用例子:

 <TextBlock Height="23" HorizontalAlignment="Left" x:Name="textBlock3" Text="{Binding ElementName=datePicker1, Path=SelectedDate,StringFormat=yyyy年MM月dd日}" VerticalAlignment="Top" Width="142" Margin="0,91,0,0" />
        <TextBlock Height="23" HorizontalAlignment="Left" Margin="0,120,0,0" Name="textBlock4"  Text="{Binding ElementName=datePicker1, Path=Text,StringFormat='Time Is :\{0\}'}" VerticalAlignment="Top" Width="142" />

将该带添加搞示例中直接运行就可以看到结果,很简单在此就不贴出运行结果了。

 

谢谢各位的支持!

 

 

posted @ 2010-11-14 23:18  星空有我  阅读(2841)  评论(6编辑  收藏  举报