我通过代码隐藏在数据网格中创建列,如下所示:
DataGridTextColumn dgtc1 = new DataGridTextColumn();
dgtc1.Header = "Feldname";
dgtc1.Binding = new Binding("FieldName");
dataGrid.Columns.Add(dgtc1);
DataGridTextColumn dgtc2 = new DataGridTextColumn();
dgtc2.Header = "Masterwert";
dgtc2.Binding = new Binding("MasterValue");
dataGrid.Columns.Add(dgtc2);
int counter = 0;
foreach (DBManager database in databases)
{
if (!database.IsMaster)
{
DataGridTextColumn dgtc = new DataGridTextColumn();
dgtc.Header = database.DisplayName;
dgtc.Binding = new Binding("LocationValues[" + counter + "]");
dataGrid.Columns.Add(dgtc);
counter++;
}
}
我希望单元格根据items属性“DeltaValues”将其背景颜色更改为特定值。
if(DeltaValues[i] == true)
//Change the background color to x
else
//Do nothing
我是否可以为代码隐藏中的列设置绑定以实现此行为?
有什么想法吗?
答案 0 :(得分:1)
我没有测试过代码。我不确定DataGridCell.ContentProperty是否是正确的属性。:
if (!database.IsMaster)
{
DataGridTextColumn dgtc = new DataGridTextColumn();
dgtc.Header = database.DisplayName;
dgtc.Binding = new Binding("LocationValues[" + counter + "]");
Setter setter = new Setter();
setter.Property = Control.BackgroundProperty;
setter.Value = Brushes.Red;
Trigger trigger = new Trigger();
trigger.Property = DataGridCell.ContentProperty;
trigger.Value = true;
trigger.Setters.Add(setter);
dgtc.CellStyle.Triggers.Add(trigger);
dataGrid.Columns.Add(dgtc);
counter++;
}
或带转换器的版本。
{
if (!database.IsMaster)
{
DataGridTextColumn dgtc = new DataGridTextColumn();
dgtc.Header = database.DisplayName;
dgtc.Binding = new Binding("LocationValues[" + counter + "]");
Converter converter = new Converter();
Binding binding = new Binding(DeltaValues[i]);
binding.Converter = converter;
dgtc.CellStyle.Setters.Add(new Setter(Control.BackgroundProperty, binding));
dataGrid.Columns.Add(dgtc);
counter++;
}
return this;
}
非常简单的转换器类:
public class Converter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if ((bool)value) return Brushes.Red;
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
new throw Exception();
}
}