基于单元格值的数据网格单元格颜色
本文关键字:单元格 数据网 网格 数据 颜色 | 更新日期: 2023-09-27 18:33:14
我有一个DataGrid
ItemsSource
viewmodel
的日期表DTableDay
。DTableDay
是内容为空或内容为"1"的单元格。我想为内容为"1"的单元格设置绿色
我的 XAML 看起来像这样
<DataGrid ItemsSource="{Binding DTableDay}" AutoGenerateColumns="True" >
<DataGridCell>
<DataGridCell.Style>
<Style TargetType="DataGridCell">
<Style.Triggers>
<Trigger Property="Content" Value="1">
<Setter Property="Background" Value="Green"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGridCell.Style>
</DataGridCell>
</DataGrid>
但是如果我运行我的应用程序,它会抛出异常
"使用项目源时操作无效。访问和 使用 ItemsControl.ItemsSource 修改元素。
谁能帮我?谢谢
您可以定义自己的DataGridTemplateColumn
。在本专栏中,您将使用简单的TextBlock
创建新DataTemplate
。将TextBlock
的Text
-属性绑定到DTableDay
集合中的对象的属性。(在下面的示例中,我假定绑定对象的属性名称为 "CellValue"
。然后,基于 TextBlock
的 Text
属性创建一个Trigger
。
<DataGrid ItemsSource="{Binding DTableDay}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding CellValue}">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<Trigger Property="Text" Value="1">
<Setter Property="Background" Value="Green"/>
</Trigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
几个问题,首先"DataGridCell"必须用DataGrid标识(即"DataGrid.DataGridCell"),否则DataGrid中的任何其他元素都不以DataGrid为前缀。 将被解释为一个项目,这意味着 ItemsSource 不能再次绑定。其次,若要设置单元格样式,请使用 DataGrid.CellStyle 属性。
<DataGrid ItemsSource="{Binding DTableDay}" AutoGenerateColumns="True" >
<DataGrid.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<!-- your style -->
</Style>
</DataGrid.CellStyle>
<DataGrid />