【问题标题】:How to change the appearance of a row within a DataGrid, based on the value of a cell, in WPF?如何在 WPF 中根据单元格的值更改 DataGrid 中行的外观?
【发布时间】:2021-10-30 05:10:55
【问题描述】:

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

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

你不应该写一个方法或一个函数:你需要写一个事件。

好的,好的,所以我开始在 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 链接到DataTable,如下:

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

如何将事件参数eDataGrid 所代表的DataTable 联系起来?

【问题讨论】:

  • 事件不会是LoadingRow,而是用户触发的任何事件,例如button_Click
  • 在 DataGrid 事件和大多数控件事件中,发送者是发生事件的 DataGrid。因此,在方法@​​987654333@ 中,您可以进行类似于:DataGrid grid = (DataGrid) sender 的直接转换。但如果只有一个网格使用该功能,您可以访问网格dg_Areas
  • @Cleptus:我有一些GUI编程经验,所以我知道sender对象。我的问题的背景思想是了解DataGridRowEventArgs。你能举个例子来说明它的用法吗?

标签: c# wpf xaml datatable datagrid


【解决方案1】:

您可以将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 定义的样式来更改视觉外观被认为是最佳实践。处理事件不是。

【讨论】:

  • 我的最终目标是在另一个 DataGrid 中的项目被选中时突出显示和修改 DataGrid 中的元组(基于ForeignKeyConstraints),所以我必须处理事件。这个问题只是我最终目标的第一步:首先突出显示一行,基于一个值。稍后,根据另一个 GUI 事件突出显示一行。
猜你喜欢
  • 1970-01-01
  • 2012-05-05
  • 2013-07-20
  • 2020-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-29
相关资源
最近更新 更多