Dynamically adding an IValueConverter in code behind
.net, c#, wpf
Solution
Use the `Converter` property of the `Binding` class:
new Binding("CanConnect") {
Converter = new IsConnectedConverter()
}
In your code, you are assigning your binding to the `Binding` property of the `DataGridTextColumn`, 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:
Style st = new Style(typeof(DataGridCell));
st.Setters.Add(new Setter(Control.BackgroundProperty, binding));
column.CellStyle = st;
In that code, `binding` would be a variable with your new `Binding` object (or the above constructor and initialization call right away). As described by the docs on `DataGridTextColumn.CellStyle`, the target type of the style must be `DataGridCell`, and as that class inherits from `Control`, we can add setters for dependency properties of `Control`, such as `Background`.
I'm afraid I can't test this code right now; I hope it gives you an idea on how to proceed.
Problem
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; } } } ```