WPF例6-布尔数据转换为显示红绿方格
2020-01-28 本文已影响0人
quchangTJU
一、如果需要转换数据格式,则需要新建一个数据转换类并且实现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
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
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<Student> { }
//数据转换类
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文件代码
<Window x:Class="WpfApp3.MainWindow"
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:local="clr-namespace:WpfApp3"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<ResourceDictionary>
<local:BoolToBrushConverter x:Key="BoolToBrushConverter"/>
</ResourceDictionary>
</Window.Resources>
<Grid>
<ListBox ItemsSource="{Binding students}" HorizontalAlignment="Left" Height="271" Margin="158,83,0,0" VerticalAlignment="Top" Width="207">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Name}" Width="100"/>
<Rectangle Width="10" Height="10" Margin="5" Fill="{Binding IsGood, Converter={StaticResource BoolToBrushConverter}}"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
代码效果如下:
