WPF例6-布尔数据转换为显示红绿方格

一、如果需要转换数据格式,则需要新建一个数据转换类并且实现IValueConverter接口,这里新建了一个BoolToBrushConverter类,如果数据为true,则返回绿色画刷,数据为false,返回红色画刷,然后在矩形的Fill属性中绑定数据,同时设定Converter属性为我们的BoolToBrushConverter类。

MainWindow.xaml.cs文件代码

using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;

namespace WpfApp3
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    public partial class MainWindow : Window
    {
        public Students students { get; set; }
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this; //设置窗口数据上下文为当前对象,ListBox控件会自动查找到students属性
            students = new Students();
            //添加几条数据
            students.Add(new Student { IsGood = false, Name = "Tom" });
            students.Add(new Student { IsGood = false, Name = "Peter" });
            students.Add(new Student { IsGood = true, Name = "Hank" });
            students.Add(new Student { IsGood = false, Name = "Nancy" });
            students.Add(new Student { IsGood = true, Name = "Tom" });

        }
    }
    public class Student
    {
        public string Name { get; set; }
        public bool IsGood { get; set; }
    }
    public class Students : ObservableCollection { }
    //数据转换类
    public class BoolToBrushConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (bool)value ? Brushes.Green : Brushes.Red;//转换器主要逻辑
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();//自动生成,本例中无需用到
        }
    }
}

MainWindow.xaml文件代码


    
        
            
        
    
    
        
            
                
                    
                        
                            
                    
                
            
        
    

代码效果如下:


WPF例6-布尔数据转换为显示红绿方格_第1张图片
代码效果

你可能感兴趣的:(WPF例6-布尔数据转换为显示红绿方格)