I currently have an object (Cell) set as a button's data context. The color of the button has to depend on a property belonging to that object (CellState); if the cell is ALIVE the background property of the Button that it's tied to is set to Black, and if the cell is DEAD the Button is White. I have to use a value converter to handle the visual representation of a cell's "state", so I have a ValueConverter that looks like this:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
SolidColorBrush b = null;
State s = (State)value;
if (s == State.ALIVE)
{
b = Brushes.Black;
}
else if (s == State.DEAD)
{
b = Brushes.White;
}
return b;
}
I'm not sure how to properly bind the button's background property to the Cell's CellState property using the value converter. This is what I have so far:
Button b = new Button();
b.DataContext = new Cell();
b.Background = Brushes.White;
b.Click += StateChangeClick_Handler;
Binding binding = new Binding();
StateToBrushConverter stateConverter = new StateToBrushConverter();
binding.Converter = stateConverter;
Cell c = (Cell)b.DataContext;
binding.ConverterParameter = c.CellState;
b.SetBinding(Button.BackgroundProperty, binding);
cellGrid.Children.Add(b);
Any help would be greatly appreciated.