简单的转化器

来源:互联网 发布:爱情动作片软件 编辑:程序博客网 时间:2024/06/04 18:12
转化器可以在xaml进行页面绑定的时候,把初始值转化为目标值。比如进行把一个color值,一个color2brush的转化器,一起绑定在canvas里面作为background的绑定值。

1)定义转化器
    [ValueConversion(typeof(Color), typeof(Brush))]
    public class ColorToBrushConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Color color = (Color)value;
            Brush brush = new SolidColorBrush(color);
            return brush;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string strValue = value.ToString();
            return value;
        }
    }

2)在xaml页面添加命名空间
xmlns:local="clr-namespace:namespace"

3)在资源中声明该转化器
<UserControl.Resources>
        <local:ColorToBrushConverter x:Key="c2bConverter"/>
</UserControl.Resources>

4)绑定
<Canvas Background="{Binding Path=SelectedColor,ElementName=colorPicker1,Converter={StaticResource c2bConverter}}" ></Canvas>
0 0
原创粉丝点击