How to change DataGrid row background color after row was edited

时间:2015-06-15 14:38:05

标签: c# .net wpf xaml datagrid

I have a DataGrid where users can edit some columns. Now I want to change the background color from the row that was edited.

I use the RowEditEnding event.

But now when a Row was edited more rows than just that one get colored.

xaml:

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

code behind:

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;
}

1 个答案:

答案 0 :(得分:0)

I've just tried such a scenario, and on that event indeed, the row color is changed. But on the next editing, the new row will have its color changed too. So we now have two rows with Background set as YellowGreen.

One suggestion would be to define row as a global variable.

  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;
  }

this way, rows edited in the past will return to their initial color. I am not sure though if this is exactly what you wanted.

You can try to add a checked flag in the model:

    private bool _IsChecked;

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

Define a converter:

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();
    }
}

And add a style for the DataGridRow:

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

In the RowEditEnding you can set that IsChecked from the model to true but then i don't know how or where do you want to set it back to false. I don't know your specific scenario but this info might be helpful. Good luck!