I’m using .NET 3.5
I have a DataGridTextColumn that I want to turn the background color red when the value of that column is false. I have seen this done in XMAL but cannot figure out how to do it in code behind
DataGridTextColumn column = new DataGridTextColumn() { Header = "Can Connect", Binding = new Binding("CanConnect") };
//How to add the converter here so that the background of the cell turns red when CanConnect = false?
public class IsConnectedConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool input = (bool)value;
switch (input)
{
case true:
return DependencyProperty.UnsetValue;
default:
return Brushes.Red;
}
}
}
Use the
Converterproperty of theBindingclass:In your code, you are assigning your binding to the
Bindingproperty of theDataGridTextColumn, but that property only controls the contents of the cell. For the visual appearance of the cell, you will need a style, which can also be set in code-behind:In that code,
bindingwould be a variable with your newBindingobject (or the above constructor and initialization call right away). As described by the docs onDataGridTextColumn.CellStyle, the target type of the style must beDataGridCell, and as that class inherits fromControl, we can add setters for dependency properties ofControl, such asBackground.I’m afraid I can’t test this code right now; I hope it gives you an idea on how to proceed.