Datagrid单元格颜色基于单元格值

时间:2016-02-03 19:00:40

标签: c# wpf xaml datagrid

DataGrid ItemsSource来自DTableDay的{​​{1}}日期表viewmodel。在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>

但是,如果我运行我的应用程序,它会抛出

的异常
  

当ItemsSource正在使用时,操作无效。访问和   改为使用ItemsControl.ItemsSource修改元素。

有人能帮帮我吗?感谢

2 个答案:

答案 0 :(得分:2)

您可以定义自己的DataGridTemplateColumn。在此列中,您可以使用简单的DataTemplate创建新的TextBlock。您可以将TextBlock&#39; Text - 属性绑定到DTableDay集合中对象的属性。 (在下面的示例中,我假设绑定对象的属性名称为"CellValue"。)然后,您基于Trigger的{​​{1}}属性创建Text

TextBlock

答案 1 :(得分:0)

一些问题,首先必须使用DataGrid(即“DataGrid.DataGridCell”)标识“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 />
相关问题