Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 865
artos Avatar asked May 12 '26 07:05

artos


1 Answers

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;
like image 69
denis morozov Avatar answered May 14 '26 23:05

denis morozov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!