I have a class having a Boolean member and I want to populate a Wpf ListBox with a collection of my class.
I want the background of the listboxitem to a different color if my boolean property is false. Is it possible with XAML ? What is the best way to do that ?
class Mi
{
public bool mybool{get;set;}
}
...
List<Mi> mycollection;// the datacontext
Here’s a quick general converter for booleans that allows you to specify a value for true and something different for false for properties of any type.
[ValueConversion(typeof(bool), typeof(object))] public class BooleanValueConverter : IValueConverter { public object FalseValue { get; set; } public object TrueValue { get; set; } #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return (bool)value ? this.TrueValue : this.FalseValue; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return object.Equals(this.TrueValue, value) ? true : false; } #endregion }Use it like so.
<SolidColorBrush x:Key="TrueBrush" Color="Green" /> <SolidColorBrush x:Key="FalseBrush" Color="Red" /> <local:BooleanValueConverter x:Key="BooleanBackground" TrueValue="{StaticResource TrueBrush}" FalseValue="{StaticResource FalseBrush}" /> ... Background="{Binding Path=Some.PropertyPath.Ending.With.A.Boolean, Converter={StaticResource BooleanBackground}}" />