How to change background color of DataGrid row after row editing

I have DataGrid

where users can edit some columns. Now I want to change the background color from the edited line.

I am using event RowEditEnding

.

But now that more rows have been edited in Row than just color.

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

      

+3


source to share


1 answer


I just tried a scenario like this, and in this case the line color actually changed. But the next time you edit the new line, it will also change its color. So now we have two lines with a background set as YellowGreen.

One suggestion is to define a string 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;
  }

      

thus, lines that have been edited in the past are reverted to their original color. I'm not sure though if this is exactly what you wanted.

You can try adding a checkbox flag to the model:

    private bool _IsChecked;

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

      



Define the 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 style for DataGridRow:

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

      

In RowEditEnding, you can set IsChecked from the model to true, but then I don't know how or where you want to return false. I don't know your specific scenario, but this information might be helpful. Good luck!

0


source







All Articles