【问题标题】:How to change DataGrid row background color after row was edited如何在编辑行后更改 DataGrid 行背景颜色
【发布时间】:2015-08-31 02:45:06
【问题描述】:

我有一个DataGrid,用户可以在其中编辑一些列。 现在我想更改已编辑行的背景颜色。

我使用RowEditEnding 事件。

但是现在,当编辑行时,多行会被着色。

xaml:

<DataGrid  x:Name="dgArtikel" ItemsSource="{Binding listViewItems}" AutoGenerateColumns="False" RowEditEnding="dgArtikel_RowEditEnding" CanUserAddRows="False">

后面的代码:

private void dgArtikel_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
    listViewItems itm = (listViewItems)dgArtikel.SelectedItem;
    DataGridRow row = dgArtikel.ItemContainerGenerator.ContainerFromItem(itm) as DataGridRow;
    row.Background = Brushes.YellowGreen;
}

【问题讨论】:

  • 感谢您提出这个问题!这是对“如何通过该行内的类实例查找 DataGrid 行”的答案。我认为这个评论会帮助其他人你的代码。

标签: c# .net wpf xaml datagrid


【解决方案1】:

我刚刚尝试过这样的场景,并且确实在那个事件中,行颜色发生了变化。但是在下一次编辑时,新行的颜色也会改变。所以我们现在有两行背景设置为 YellowGreen。

一个建议是将行定义为全局变量。

  private DataGridRow row;
  private void dgArtikel_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
  {
   if (row != null)
      row.Background = Brushes.White;

   listViewItems itm = (listViewItems)dgArtikel.SelectedItem;
   row = dgArtikel.ItemContainerGenerator.ContainerFromItem(itm) as DataGridRow;
   row.Background = Brushes.YellowGreen;
  }

这样,过去编辑的行将返回其初始颜色。我不确定这是否正是您想要的。

您可以尝试在模型中添加选中标志:

    private bool _IsChecked;

    public bool IsChecked
    {
        get { return _IsChecked; }
        set
        {
            _IsChecked = value;
            PropertyChanged(this, new PropertyChangedEventArgs("IsChecked"));
        }
    }

定义一个转换器:

public class BoolToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        bool val = (bool) value;
        if (val)
            return Brushes.GreenYellow;
        else
        {
            return Brushes.White;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

并为 DataGridRow 添加样式:

    <Style TargetType="DataGridRow">
         <Setter Property="Background" Value="{Binding IsChecked, Converter={StaticResource BoolToColorConverter}}"></Setter>
    </Style>

在 RowEditEnding 中,您可以将模型中的 IsChecked 设置为 true,但我不知道您希望如何或在何处将其设置回 false。我不知道您的具体情况,但此信息可能会有所帮助。祝你好运!

【讨论】:

    猜你喜欢
    • 2011-05-11
    • 2011-04-29
    • 2012-05-25
    • 2015-08-22
    • 1970-01-01
    • 2015-03-26
    • 2016-03-15
    • 2023-01-16
    • 2012-12-05
    相关资源
    最近更新 更多