WPF工具包DataGridCell样式DataTrigger

Kri*_*rip 3 c# wpf datagrid datatrigger wpftoolkit

如果在DataGrid中更新了值,我试图将单元格的颜色更改为黄色.

我的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>
Run Code Online (Sandbox Code Playgroud)

网格绑定到数组列表(显示类似于excel的值表).数组中的每个值都是一个包含IsDirty依赖项属性的自定义对象.更改值时,将设置IsDirty属性.

当我运行这个:

  • 更改第1列中的值=整行变为黄色
  • 更改任何其他列中的值=没有任何反应

我希望只有更改的单元格变为黄色,无论它在哪个列中.你看到我的XAML有什么问题吗?

rep*_*pka 8

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

由于您的示例显示您已AutoGenerateColumns设置为false,因此我假设您自己生成列DataGridTextColumn,其Binding属性设置为绑定到实际值字段.要将单元格样式更改为黄色,您必须更改CellStyle每个样式DataGridColumn:

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);
}
Run Code Online (Sandbox Code Playgroud)

您可以尝试使用更改DataContext每个单元格DataGridColumn.CellStyle.也许只有这样你才能直接从网格级样式将单元格绑定到'IsDirty',而不是单独为每个列执行.但我没有实际数据模型,你必须测试这个.