在DataGrid中根据其值设置单元格样式

时间:2015-02-28 21:41:32

标签: c# wpf datagrid

我有DataGrid的值。我想检查每个单元格,如果值不在两个数字(限制)之间,我想将背景更改为红色。 DataGrid的每列的限制都不同。我试图通过更改ColumnStyle的{​​{1}}方法中的OnAutoGeneratingColumn来实现它,但到目前为止我还没有成功。你能看看我的代码有什么问题吗?

DataGrid方法:

OnAutoGeneratingColumn

protected override void OnAutoGeneratingColumn(DataGridAutoGeneratingColumnEventArgs e) { //The first yolumn with date I dont want to alter if (Columns.Count == 0) { base.OnAutoGeneratedColumns(e); } else { //Trigger to chech if the number is lower than the bottom limit DataTrigger lowerTrigger = new DataTrigger(); lowerTrigger.Binding = new Binding("Content") { Converter = new LessThanConverter(), ConverterParameter = SelectedDevices[this.Columns.Count - 1].minValue }; lowerTrigger.Value = "True"; lowerTrigger.Setters.Add(new Setter(DataGridCell.BackgroundProperty, Brushes.Red)); //Trigger to check if the number is higher than the top limit DataTrigger higherTrigger = new DataTrigger(); higherTrigger.Binding = new Binding("Content") { Converter = new LessThanConverter(), ConverterParameter = SelectedDevices[this.Columns.Count - 1].maxValue }; higherTrigger.Value = "False"; higherTrigger.Setters.Add(new Setter(DataGridCell.BackgroundProperty, Brushes.Red)); //Multi triger to check, whether the number is between the tow limits MultiDataTrigger betweenTrigger = new MultiDataTrigger(); Condition conditionMin = new Condition(); conditionMin.Binding = new Binding("Content") { Converter = new LessThanConverter(), ConverterParameter = SelectedDevices[this.Columns.Count-1].minValue }; conditionMin.Value = "False"; Condition conditionMax = new Condition(); conditionMax.Binding = new Binding("Content") { Converter = new LessThanConverter(), ConverterParameter = SelectedDevices[this.Columns.Count - 1].maxValue }; conditionMax.Value = "True"; betweenTrigger.Conditions.Add(conditionMax); betweenTrigger.Conditions.Add(conditionMin); betweenTrigger.Setters.Add(new Setter(DataGridCell.BackgroundProperty, Brushes.Blue)); Style style = new Style(typeof(DataGridCell)); style.Triggers.Add(lowerTrigger); //style.Triggers.Add(betweenTrigger); style.Triggers.Add(higherTrigger); e.Column.CellStyle = style; base.OnAutoGeneratedColumns(e); } } 类:

LessThanConverter

1 个答案:

答案 0 :(得分:1)

所以最后我找到了解决方案。我的错误是,无法像我new Binding("Content")那样绑定转换器的值。正确的解决方案是将它绑定到列的名称,这可以在运行时使用e.Column.Header.ToString()完成,而不是工作!