如果要在视图模型端设置单元格颜色并绑定其属性,可以使用 CellBinding 函数轻松完成。
// 模型端 (SampleDataItem.cs)
公共类SampleDataItem
{
public int ID { get ; set ; _
公共字符串值 1 {获取;设置;
public SolidColorBrush Value1Color { get ; set ; } // 设置为 Value1 单元格背景颜色的颜色
}
// 视图模型端 (MainWindowViewModel.cs)
公共类MainWindowViewModel
{
私有ObservableCollection < SampleDataItem > _sampleData;
public ObservableCollection < SampleDataItem >样本数据
{
得到{返回_sampleData ;
设置{ _sampleData =值; }
}
公共MainWindowViewModel ()
{
// ID=1使Value1单元格的背景色为Pink,ID=4使Value1单元格的背景色为LightGreen,其他为透明
_sampleData = new ObservableCollection < SampleDataItem >() ;
_sampleData.Add ( new SampleDataItem () { ID = 1 , Value1 = "aaa" , Value1Color = new SolidColorBrush ( Colors.Pink ) }) ;
_sampleData.Add ( new SampleDataItem () { ID = 2 , Value1 = "bbb" , Value1Color = new SolidColorBrush ( Colors.Transparent ) }) ;
_sampleData.Add ( new SampleDataItem () { ID = 3 , Value1 = "ccc" , Value1Color = new SolidColorBrush ( Colors.Transparent ) }) ;
_sampleData.Add ( new SampleDataItem ( ) { ID = 4 , Value1 = "ddd" , Value1Color = new SolidColorBrush ( Colors.LightGreen ) } ) ;
_sampleData.Add ( new SampleDataItem () { ID = 5 , Value1 = "eee" , Value1Color = new SolidColorBrush ( Colors.Transparent ) } ) ;
}
}
<!-- 视图端 (MainWindow.xaml) -->
< igDP:XamDataGrid ...
DataSource = "{BindingSampleData}" ... >
< igDP:XamDataGrid.FieldLayoutSettings >
< igDP:FieldLayoutSettings AutoGenerateFields = "False" />
< /igDP:XamDataGrid.FieldLayoutSettings >
< igDP:XamDataGrid.FieldLayouts >
< igDP:FieldLayout >
< igDP:FieldLayout.Fields >
< igDP:Field Name = "ID"标签= "ID" />
< igDP:Field Name = "Value1" Label = "Value1" >
<!-- 使用 CellBinding 将单元格的背景色与视图模型端的属性绑定 -->
< igDP:Field.CellBindings >
< igDP:CellBinding
财产= “背景”
Target = "CellValuePresenter"
Binding = "{Binding Path=DataItem.Value1Color}" />
< /igDP:Field.CellBindings >
</ igDP:字段>
< /igDP:FieldLayout.Fields >
</ igDP:FieldLayout >
< /igDP:XamDataGrid.FieldLayouts >
</ igDP:XamDataGrid >
执行结果