tags:

views:

19

answers:

2

I want to bind a control fill color to a boolean in c#, so if it is false, the color is Red and if it is true, the color is Green.

Pretty new to XAML, but want to get into good habits from the start.

Thanks,

Ben

+1  A: 

View models exist to convert data into a format that the UI can use, so create a property of type Color in the ViewModel for the form that does the logical conversion from the stored boolean value to a Color value. Call this property 'DisplayColor'.

Use the INotifyPropertyChanged interface on the ViewModel to raise events on the 'DisplayColor' property every time the boolean value changes colour (if it changes over time). This will ensure that the UI updates itself whenever the boolean value changes.

Then bind the color property of the control to the view model's new 'DisplayColor' property (you will have set the DataContext to the ViewModel, presumably).

I did this for the first time just yesterday :)

Dr Herbie
+1  A: 

You could also implement an IValueConverter which performs the conversion between Boolean and Color. Then just bind the color property directly to the Boolean, but specify your new IValueConverter in the binding.

This approach can be especially useful when you don't have control over the classes you're binding to.

For more information, see http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx.

Alex Humphrey