WPF DataGrid - 如何设置正确的 DataTrigger 绑定到单元格的数据源(而不是行的源)

WPF DataGrid - How to setup correct DataTrigger binding to cell's data source (and not row's source)

尝试在 WPF DataGrid 中设置依赖于单元格对象 属性 的单元格背景时出现错误,未找到 属性(但在行对象上):

System.Windows.Data Error: 40 : BindingExpression path error: 'IsOn' property not found on 'object' ''MyRow' (HashCode=48826322)'. BindingExpression:Path=IsOn; DataItem='MyRow' (HashCode=48826322); target element is 'DataGridCell' (Name=''); target property is 'NoTarget' (type 'Object')

我想知道,为什么 DataTrigger Binding 正在寻址行对象“MyRow”,因为 DataTrigger 被定义为 for/inside 一个 CellStyle。

XAML:

<DataGrid Name="tblTest" Grid.Column="2" IsReadOnly="True" AutoGenerateColumns="True">
    <DataGrid.CellStyle>
        <Style TargetType="{x:Type DataGridCell}">
            <Setter Property="Background" Value="PaleGreen" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsOn}" Value="True">
                    <Setter Property="Background" Value="Red"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.CellStyle>
</DataGrid>

C#

class MyCell
{
    public MyCell( string v)
    {
        Value = v;
    }
    public string Value { get; set; }
    public bool IsOn { get => Value == "one";  }
    public override string ToString()
    {
        return Value;
    }
}

class MyRow
{
    public MyCell One { get; set;  }
    public MyCell Two { get; set;  }
}

void SetupTestTable()
{
    List<MyRow> data = new();
    data.Add(new MyRow
    {
        One = new MyCell("one"),
        Two = new MyCell("two")
    });
    tblTest.ItemsSource = data;
}

那么如何正确绑定单元格对象“MyCell”呢?

DataGridCells 与 DataGridRow 具有相同的 DataContext - 以通用方式进行不同操作有很多障碍。所以单身DataGrid.CellStyle不行

我将使用 AutoGeneratingColumn 为每列创建单元格样式。但是,它们将基于存储在 DataGrid.Resources.

中的现有样式
<DataGrid Name="tblTest" Grid.Column="2" IsReadOnly="True" 
          AutoGenerateColumns="True"
          AutoGeneratingColumn="tblTest_AutoGeneratingColumn">
    <DataGrid.Resources>
        <Style TargetType="{x:Type DataGridCell}" x:Key="ColoredCellStyle">
            <Setter Property="Background" Value="Cyan" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding Tag.IsOn, RelativeSource={RelativeSource Self}}" Value="True">
                    <Setter Property="Background" Value="Red"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.Resources>
</DataGrid>

我正在使用绑定到 Tag 而不是 DataContext,因为 DataContext 是 MyRow 对象。在 Tag 中将有 MyCell 个对象。在事件处理程序中实现:

private void tblTest_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    if (e.Column is DataGridTextColumn tc && tc.Binding is Binding binding)
    {
        // unique value for each column
        var property = binding.Path.Path;

        // DataGrid reference to get Resources
        var dg = (DataGrid)sender;

        // new cell style which inherits trigger from ColoredCellStyle and binds Tag to MyCell property
        var cellStyle = new Style
        {
            TargetType = typeof(DataGridCell),
            BasedOn = (Style)dg.Resources["ColoredCellStyle"],
            Setters =
            {
                new Setter
                { 
                    Property = DataGridCell.TagProperty, 
                    Value = new Binding(property)
                }
            }
        };

        tc.CellStyle = cellStyle;
    };
}