如何在 WPF 中根据单元格的值更改 DataGrid 中一行的外观?

How to change the appearance of a row within a DataGrid, based on the value of a cell, in WPF?

由于我是 C# WPF 的新手,我尝试使用试错法尝试一下。

我想做的是根据某些用户操作更改 DataGrid 中一行的外观。
但是,通过阅读互联网上的信息,我了解到“正确”的方法是:

You should not write a method or a function: you need to write an event.

好吧,好吧,所以我开始在 XAML:

<DataGrid x:Name="dg_Areas" ... LoadingRow="View_dg_Areas"/>

显然,View_dg_Areas 事件处理程序应具有以下签名:

private void View_dg_Areas(object sender, DataGridRowEventArgs e) { }

然后呢?

我开始,很幼稚,如下:

private void View_dg_Areas(object sender, DataGridRowEventArgs e)
{
    System.Diagnostics.Debug.WriteLine(e.ToString());
    System.Diagnostics.Debug.WriteLine(e.Row.ToString());
    System.Diagnostics.Debug.WriteLine(e.Row.Item.ToString());
}

我的想法是从中学习如何找到相应行的信息(有没有办法读取特定列的值?),但我一无所获。

我可以告诉你DataGrid被link编辑成DataTable,如下:

dg_Areas.ItemsSource = dataSet.Tables["Areas"].DefaultView;

如何 link 事件参数 eDataTable DataGrid 代表?

您可以将 RowStyle 与绑定到您的属性或列之一的 DataTrigger 结合使用:

<DataGrid x:Name="dg_Areas">
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Style.Triggers>
                <DataTrigger Binding="{Binding YourColumn}" Value="SomeValue">
                    <Setter Property="Background" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

上面的示例标记更改了“YourColumn”等于“SomeValue”的行的背景颜色。

使用 XAML 定义的样式来更改视觉外观被认为是最佳做法。处理事件不是。