当前位置:   article > 正文

WPF转换器

wpf转换器

学习测试了别人写的转换器,记录一下:

1、定义数据源类型:

public class ConverterViewModel
{
    public IList<ColorInfo> ColorList { get; set; }
    public int SelectedColor { get; set; }
    public ConverterViewModel()
    {
        ColorList = new List<ColorInfo>()
        {
            new ColorInfo() {ID = 0,Name = "red"},
            new ColorInfo() {ID = 1,Name = "green"},
            new ColorInfo() {ID = 2,Name = "blue" }
        };
        SelectedColor = 0;
    }
}

public class ColorInfo
{
    public int ID { get; set; }
    public string Name { get; set; }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

2、定义转换器

public class ColorConverter : IValueConverter
{
    public static Color[] ColorCollection = new Color[]
    {
        Color.FromRgb(255,0,0),
        Color.FromRgb(0,255,0),
        Color.FromRgb(0,0,255)
    };

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
        {
            return new SolidColorBrush(ColorCollection[0]);
        }
        try
        {
            return new SolidColorBrush(ColorCollection[(int)value]);
        }
        catch (Exception)
        {
            return new SolidColorBrush(ColorCollection[0]);
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

3、XAML代码:

<ComboBox  Cursor="Hand" Name="ComboBox_ColorSelect" Height="25" Width="80"
 ItemsSource="{Binding ColorList}" SelectedValuePath="ID"  DisplayMemberPath="Name" 
 SelectedValue="{Binding SelectedColor}"/>
 
    <TextBlock Background="{Binding SelectedValue,ElementName=ComboBox_ColorSelect,Converter={StaticResource ColorConverter}}" 
    Height="25" Width="80"/>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

4、xaml.cs代码:

public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new ConverterViewModel();
    }
  • 1
  • 2
  • 3
  • 4
  • 5
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/537630
推荐阅读
相关标签
  

闽ICP备14008679号