Search code examples
wpfdatagridforeground

wpf datagrid row Foreground in code behind


I don't want to use MVVM and want to change the selected row Foreground on my datagrid in code behind (in SelectionChanged EventHandler function), but I can't find the solid way.

My row can be black, blue and red, but shows the color with a higher priority based on some condition. After selecting the current row I should remove, f.e. black color from my priority list.

I have some class:

public class TempClass{ public string cell1 { get; set; }; public string cell2 { get; set; };}

and

TempClass[] collection; 

bound with my datagrid:

datagrid.ItemsSource = collection;

Any idea?


Solution

  • var rowStyle = new Style {TargetType = typeof (DataGridRow)};
    rowStyle.Setters.Add(new Setter(ForegroundProperty, Brushes.Green));
    var rowTrigger = new Trigger {Property = DataGridRow.IsSelectedProperty, Value = true};
    rowTrigger.Setters.Add(new Setter(ForegroundProperty, Brushes.Red));
    rowTrigger.Setters.Add(new Setter(BackgroundProperty, Brushes.Orange));
    rowStyle.Triggers.Add(rowTrigger);
    
    var cellStyle = new Style {TargetType = typeof (DataGridCell)};
    var cellTrigger = new Trigger {Property = DataGridCell.IsSelectedProperty, Value = true};
    cellTrigger.Setters.Add(new Setter(ForegroundProperty, Brushes.Red));
    cellTrigger.Setters.Add(new Setter(BackgroundProperty, Brushes.Orange));
    cellStyle.Triggers.Add(cellTrigger);
    
    datagrid.RowStyle = rowStyle;
    datagrid.CellStyle = cellStyle;