silverlight 使用IValueConverter 转换

在绑定数据中 有时候我们需要转换相关数据类型 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();

    

//string _value = value.ToString();
//if (_value != null)
//{
// //MessageBox.Show(_value + " if");
// return ((_value).Equals("1") ? "启用" : "停用");
//}
//else
//{
// //MessageBox.Show(value + " else");
// return 33;
//}


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

//if (targetType != typeof(int)) throw new InvalidOperationException("转换的值必须是字符!");
//return (value.ToString() == "启用" ? 1 : 0);


            return value.ToString();
        }
然后xaml代码 
<UserControl x:Class="SilverlightApplication1.convertControl"
    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"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" xmlns:my="clr-namespace:SilverlightApplication1">
    <UserControl.Resources>
        <my:DataTimeConvert x:Key="DataTimeConvert1" /> //这是转换实例化
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White">
        <TextBox Height="23" HorizontalAlignment="Left" Margin="32,23,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
       <TextBox Height="23" HorizontalAlignment="Left" Margin="170,23,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" Text="{Binding Path=Text, Mode=TwoWay, ElementName=textBox1, Converter={StaticResource DataTimeConvert1}}" />
    </Grid>
</UserControl>

请用vs 在转换类型中两个方法设置断点 在浏览器测试输入文字进行观察

原文地址:https://www.cnblogs.com/meimao5211/p/3464926.html