2010-05-13 72 views
3

我试图将单元格的颜色更改为黄色,如果该值已在DataGrid中更新。WPF工具包DataGridCell样式DataTrigger

我XAML:

<toolkit:DataGrid x:Name="TheGrid" 
        ItemsSource="{Binding}" 
        IsReadOnly="False" 
        CanUserAddRows="False" 
        CanUserResizeRows="False" 
        AutoGenerateColumns="False" 
        CanUserSortColumns="False"        
        SelectionUnit="CellOrRowHeader" 
        EnableColumnVirtualization="True" 
        VerticalScrollBarVisibility="Auto" 
        HorizontalScrollBarVisibility="Auto"> 
    <toolkit:DataGrid.CellStyle> 
     <Style TargetType="{x:Type toolkit:DataGridCell}"> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding IsDirty}" Value="True"> 
        <Setter Property="Background" Value="Yellow"/> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </toolkit:DataGrid.CellStyle> 
</toolkit:DataGrid> 

网格被绑定到阵列的列表(显示值的表种如Excel会)。数组中的每个值都是一个包含IsDirty依赖项属性的自定义对象。当值更改时,IsDirty属性被设置。

当我运行此:

  • 变化列中的值1 =整排进黄
  • 变化的值在任何其他列=什么也没有发生

我只想要改变细胞无论其中哪一列都变黄。你看到我的XAML有什么问题吗?

回答

7

发生这种情况的原因是因为DataContext设置在行级别,并且每个DataGridCell都不会更改。因此,当绑定到IsDirty时,它绑定到行级数据对象的属性,而不是单元级数据对象的属性。

由于您的例子表明,你有AutoGenerateColumns设置为false,我假设你生成列自己有类似DataGridTextColumnBinding属性设置为结合实际值字段。若要单元格样式变为黄色,你不得不在每个DataGridColumn喜欢这种改变CellStyle

foreach (var column in columns) 
{ 
    var dataColumn = 
     new DataGridTextColumn 
      { 
       Header = column.Caption, 
       Binding = new Binding(column.FieldName), 
       CellStyle = 
       new Style 
        { 
         TargetType = typeof (DataGridCell), 
         Triggers = 
          { 
           new DataTrigger 
            { 
             Binding = new Binding(column.FieldName + ".IsDirty"), 
             Setters = 
              { 
               new Setter 
                { 
                 Property = Control.BackgroundProperty, 
                 Value = Brushes.Yellow, 
                } 
              } 
            } 
          } 
        } 
      }; 
    _dataGrid.Columns.Add(dataColumn); 
} 

您可以使用DataGridColumn.CellStyle改变每个单元的DataContext实验。也许只有这样,你才能像单独一样直接从网格级风格将单元格绑定到“IsDirty”,而不必单独为每个列进行。但是我没有实际的数据模型来测试它。

+0

太棒了!这工作正是我需要它。我唯一需要改变的是为DataTrigger添加一个Value = true(因此当IsDirty为true时触发) – KrisTrip 2010-05-19 21:48:37

+1

我正在尝试完成此操作,但是在xaml中编写了我的样式?这可能吗? – jrwren 2011-06-10 19:33:18

+0

这太好了。但是 - 我试图在WPF中这样做,这似乎是来自System.Windows.Controls命名空间的代码。有没有办法在System.Windows.Forms中做类似的事情?我无法在任何地方找到资源。谢谢! – mpsyp 2017-09-07 16:29:03