2012-07-06 50 views
1

我不想使用MVVM,并且想要在代码后面(在SelectionChanged EventHandler函数中)在我的数据网格上更改选定的行Foreground,但我无法找到可靠的方式。wpf datagrid row前面代码中的代码

我的行可以是黑色,蓝色和红色,但会根据某些条件显示具有更高优先级的颜色。选择当前行后,我应该删除,f.e.我优先列表中的黑色。

我有一些类:

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

TempClass[] collection; 

绑定了我的DataGrid:

datagrid.ItemsSource = collection; 

任何想法?

+1

您应该先阅读[this](http://meta.stackexchange.com/a/5235/186207)。 – LPL 2012-07-06 17:54:06

回答

1
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; 
+0

感谢您的回答,但我想在代码后面的数据网格中更改** SELECTED **行前景。我的行可以是黑色,蓝色和红色,但根据某些条件显示具有更高优先级的颜色。选择当前行后,我应该删除,f.e.我优先列表中的黑色。 – artos 2012-07-07 12:03:56

+0

我明白了,我更新了关于如何在.cs中编写触发器的示例的答案 – 2012-07-09 16:51:22

+1

非常感谢,样式和安装程序很好,您可以在答案中添加如何到达选定“DataGridRow ''在我的dataGrid中,因为我有'TempClass []集合;''和'datagrid.ItemsSource =集合;'。当我试图得到选择'DataGridRow'如: 'DataGridRow currentRow = datagrid.SelectedItem作为DataGridRow' currentRow为空; – artos 2012-07-09 18:13:44