Search code examples
wpfdatagridcolorsrowselectionchanged

WPF DataGrid SelectionChanged Row Color


I would like change the color of the whole row if a condition is true in the SelectionChanged Event from a WPF DataGrid. I can change the color in the LoadingRow Event if I use the arg DataGridRowEventArgs e. I can use e.Row.Background = new SolidColorBrush(Colors.White). But this dosen't work in the SelectionChangedEvent. How do I can convert from a DataGrid to DataGridRow to use DataGridRow.Row.Background = new SolidColorBrush(Colors.White)? Thank you for your understanding.

    private void grd_SelectionChanged(object sender, SelectionChangedEventArgs e)
     {

         int iIndex = grd.SelectedIndex;
         SolidColorBrush myColor = new SolidColorBrush(Colors.Tomato);

         if (grd.SelectedItem != null)
         {
             // var datagridrow = grd.SelectedItem as DataGridRow; --> dosent'work
             var drw = grd.SelectedItem as DataRowView;



             DataRow row = drw.Row;
             if (Convert.ToBoolean(row["Checkbox"]) == true)
             {
                 row["Checkbox"] = false;
             }
             else
             {
                 row["Checkbox"] = true;    
                 // change the background color of the row too what ever  
                 // white red blue                          
              }
         }
    }

================================================================================

here ist the xaml and code. Thank you a lot

MainWindow.xaml.cs

     namespace DataGridBrushRowColor
    {

       public partial class MainWindow : Window
    {
    public MainWindow()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        CreateTable myDog = new CreateTable();
        // Lade Daten
        dataGrid1.AutoGenerateColumns = true;

        DataView myView = new DataView(myDog.DogOutput);
        dataGrid1.DataContext = myView;            
    }

    private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var rowview = dataGrid1.SelectedItem as DataRowView;
        if (rowview != null)
        { 
            DataRow row = rowview.Row;
            if (Convert.ToBoolean(rowview["Choice"]) == true)
            {
                row["Choice"] = false;
            }
            else
            {
                row["Choice"] = true;
                // Color the whole row red

            }
        }


     }
     }
     }

MainWindow.xaml

     <Window x:Class="DataGridBrushRowColor.MainWindow"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     Title="MainWindow" Height="350" Width="525">
    <Grid>
    <DataGrid AutoGenerateColumns="False" HorizontalAlignment="Left" Name="dataGrid1" VerticalAlignment="Top" Height="243" Width="503" ItemsSource="{Binding}" SelectionChanged="dataGrid1_SelectionChanged" >

    </DataGrid>
    <Button Content="Button" Height="26" HorizontalAlignment="Left" Margin="12,249,0,0" Name="button1" VerticalAlignment="Top" Width="100" Click="button1_Click" />
</Grid>

CreateTable.cs

    namespace DataGridBrushRowColor
    {
        class CreateTable
        {
            DataTable dtDog;

    public DataTable DogOutput
    {
        get
        {
            return dtDog;
        }
    }


    public CreateTable()
    {
        // Here we create a DataTable with four columns.
        DataTable table = new DataTable();
        table.Columns.Add("Choice", typeof(Boolean));
        table.Columns.Add("Weight", typeof(int));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Breed", typeof(string));
        table.Columns.Add("Date", typeof(DateTime));

        // Here we add five DataRows.            
        table.Rows.Add(false,57, "Koko", "Shar Pei", DateTime.Now);
        table.Rows.Add(false,130, "Fido", "Bullmastiff", DateTime.Now);
        table.Rows.Add(false, 92, "Alex", "Anatolian Shepherd Dog", DateTime.Now);
        table.Rows.Add(false, 25, "Charles", "Cavalier King Charles Spaniel", DateTime.Now);
        table.Rows.Add(false, 7, "Candy", "Yorkshire Terrier", DateTime.Now);
        dtDog = table;


    }

    }
    }

Solution

  • you can achive the same thing by using styles and triggers as like below.

      <Window.Resources>
            <local:MyColorConverter x:Key="colorconverter" />
            <Style TargetType="{x:Type DataGridRow}">
                <Style.Triggers>
                    <Trigger Property="IsSelected" Value="True">
                        <Setter Property="Background" Value="{Binding Converter={StaticResource colorconverter}}" /> 
                     </Trigger>              
                </Style.Triggers>
            </Style>
        </Window.Resources>
    

    ..code behind chagnes

    public class MainWindow:Windows
    {
    your codes.
    }
    
     public class MyColorConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                SolidColorBrush brush = new SolidColorBrush(Colors.Black);
                bool result = false;
                if (value != null)
                {
                    DataRowView drv = value as DataRowView;
                    try
                    {
                        if (drv != null)
                            if (Boolean.TryParse(drv.Row["Choice"].ToString(), out result))
                            {
                                if (result)
                                    brush = new SolidColorBrush(Colors.Red);
    
                                else if (result == false)
                                    brush = new SolidColorBrush(Colors.YellowGreen);
                            }
                    }
                    catch { }
                }
                return brush;
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }