在绑定数据中 有时候我们需要转换相关数据类型 silverlight提供了一个System.Windows.Data.IValueConverter接口

它提供两个方法 Convert和ConvertBack  前者是资源到目标元素时转换  后者是目标到资源时转换

先创建一个类型

 public class DataTimeConvert : System.Windows.Data.IValueConverter
    {

        // 参数:
        //   value:
        //     正传递到源的目标数据。
        //
        //   targetType:
        //     源对象需要的数据的 System.Type。
        //
        //   parameter:
        //     要在转换器逻辑中使用的可选参数。
        //
        //   culture:
        //     转换的区域性。
        //
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return  (value).ToString();
        }
        // 参数:
        //   value:
        //     正传递到源的目标数据。
        //
        //   targetType:
        //     源对象需要的数据的 System.Type。
        //
        //   parameter:
        //     要在转换器逻辑中使用的可选参数。
        //
        //   culture:
        //     转换的区域性。
        //
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value.ToString();
        }

然后xaml代码

 

<UserControl x:Class="TemplateConvert.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
     xmlns:convert="clr-namespace:TemplateConvert"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <UserControl.Resources>
        <convert:TextChange x:Key="txtChange"></convert:TextChange>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White">
        <ListBox x:Name="lblist">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Title,Converter={StaticResource txtChange}}" x:Name="tbTest" ></TextBlock> 
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
       
        </Grid>
</UserControl>

 

 

posted on 2013-05-09 13:45  aking96  阅读(232)  评论(0编辑  收藏  举报