2016-02-03 134 views
1

我有DataGridItemsSource DateTable DTableDay from viewmodel。在DTableDay中是内容为空或内容为“1”的单元格。我想设置绿色与内容的单元格“1”基于单元值的Datagrid单元格颜色

我的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正在使用时操作无效Access和 用ItemsControl.ItemsSource修改元素代替

任何人都可以帮助我吗?谢谢

+0

它看起来像你正在做的单元格颜色正确更改。你看到的异常可能是你在代码的不同部分做的事情的结果。你可以看看堆栈跟踪,看看它被抛出的方法在哪里? – Tofystedeth

回答

0

有几个问题,第一个“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 /> 
2

您可以定义自己的DataGridTemplateColumn。在本专栏中,您将使用简单的TextBlock创建新的DataTemplate。您将TextBlockText-属性绑定到DTableDay集合中的对象的属性。 (在下面的示例中,我假设绑定对象的属性名称为"CellValue"。)然后,您基于TextBlockText属性创建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>