DataContext 上的 WPF DataGrid DataTrigger 绑定 属性

WPF DataGrid DataTrigger Binding on DataContext property

DataContext 属性的正确 DataTrigger 绑定是什么? 我有一个像这样绑定的 DataGrid:

XAML:

<DataGrid x:Name="dataGrid" Grid.Row="4" Grid.ColumnSpan="2"
    ItemsSource="{Binding}"
    CellStyle="{StaticResource RowStateStyle}"
>
</DataGrid>

在 .cs 中,网格绑定到 DataTable,因此单元格的 DataContext 是 DataRowView,包含 Row 作为 属性:

// DataTable containing lots of rows/columns
dataGrid.DataContext = dataTable; 

编辑:

参考ASh的解决方案,我编辑了样式并放入了未更改和修改的触发器:

    <Style x:Key="RowStateStyle" TargetType="{x:Type DataGridCell}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=DataContext.Row.RowState,
                RelativeSource={RelativeSource Self}}" Value="Unchanged">
                <Setter Property="Foreground" Value="Green" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Path=DataContext.Row.RowState,
                RelativeSource={RelativeSource Self}}" Value="Modified">
                <Setter Property="Foreground" Value="Yellow" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Path=Content.Text,
                RelativeSource={RelativeSource Self}}" Value="test">
                <Setter Property="Foreground" Value="Red" />
            </DataTrigger>
        </Style.Triggers>
    </Style>

在 Content.Text 上触发效果非常好,Unchanged 也是如此。然而,当我修改一个单元格(因此 DataRowState = Modified)时,没有任何反应并且颜色保持绿色。有什么解决办法吗?

DataTrigger 对我有用,如果我

  1. 使用DataContext.Row.RowState路径

  2. 不要使用Mode=TwoWay

  3. 并在设置值

  4. 时删除枚举名称DataRowState
<DataTrigger Binding="{Binding Path=DataContext.Row.RowState,
             RelativeSource={RelativeSource Self}}" 
             Value="Unchanged">
    <Setter Property="Foreground" Value="Red" />
</DataTrigger>

我发现另一个 post 与此问题相关

WpfToolkit DataGrid: Highlight modified rows

没有通知有关 RowState 更改的默认机制。但是可以在派生数据表中创建一个 class:

public class DataTableExt: DataTable
{
    protected override DataRow NewRowFromBuilder(DataRowBuilder builder)
    {
        return new DataRowExt(builder);
    }

    protected override void OnRowChanged(DataRowChangeEventArgs e)
    {
        base.OnRowChanged(e);
        // row has changed, notifying about changes
        var r = e.Row as DataRowExt;
        if (r!= null)
            r.OnRowStateChanged();
    }
}

使用派生数据行 class:

public class DataRowExt: DataRow, INotifyPropertyChanged
{
    protected internal DataRowExt(DataRowBuilder builder) : base(builder)
    {
    }

    internal void OnRowStateChanged()
    {
        OnPropertyChanged("RowState");
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}