IValueConverter接口位于名称空间System.Windows.Data,接口定义了Convert和ConvertBack两组方法:
public interface IValueConverter
{
object Convert(object value, Type targetType, object parameter, CultureInfo culture);
object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture);
}
}
在界面控件所需数据类型或格式和后台绑定的数据不一致时,往往需要借助IValueConverter接口进行转换。
界面添加一个表格控件datagrid,绑定数据结构StudentList,StudentList这是一个ObservableCollection<Students>集合;
Students数据模型定义如下:其中重写了ToString方法,并定义了四个属性,分别是Id,Name ,Age 和AgeValidate ,AgeValidate 用来验证数据,即年龄小于16或者大于21,时界面字体显示红色
界面前台绑定:主要是通过这句
Foreground="{Binding AgeValidate,Converter={StaticResource ShowColorConverter}}"
datagrid全部的代码如下:
<DataGrid Name="dgSourceData" AutoGenerateColumns="False" ItemsSource="{Binding StudentList}"
ContextMenu="{Binding menu1}" RowHeaderWidth="30" SelectedItem ="{Binding SelectedItems}" SelectionMode="Single" SelectionUnit="Cell"
cal:Message.Attach="[Event SelectionChanged]=[GridControl_SelectionChanged($source,$eventArgs)];"
CellEditEnding="dgSourceData_BeginningEdit" SelectionChanged="dgSourceData_SelectionChanged" >
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{ Binding Path=Name}" MinWidth="68"/>
<DataGridTemplateColumn Header="Age" MinWidth="68" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=Age,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
Foreground="{Binding AgeValidate,Converter={StaticResource ShowColorConverter}}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="Id" Binding="{ Binding Path=Id}" MinWidth="48"/>
</DataGrid.Columns>
</DataGrid>
定义资源
<UserControl.Resources>
<converters:ShowColorConverter x:Key="ShowColorConverter" />
</UserControl.Resources>
IValueConverter接口实现:注意需要将object类型的value转换为我们的目标类型bool量
public class ShowColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var flag = (bool)value;
if (flag)
{
return "Red";
}
else
{
return "Black";
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}