tags:

views:

22

answers:

3

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
+1  A: 

You could achieve this with a DataTemplateSelector, having two templates with differing backgrounds.

A better way would probably be to bind the the background property to your boolean and use an IValueConverter which would return an appropriate colour.

Background="{Binding Path=mybool, Converter={StaticResource boolToBackgroundConverter}}"

benPearce
+4  A: 

You could use a DataTrigger:

<DataTemplate DataType="{x:Type my:Mi}">
    <Grid>
        <Grid.Style>
            <Style TargetType="Grid">
                <Setter PropertyName="Background" Value="White" />

                <Style.Triggers>
                    <DataTrigger Binding="{Binding mybool}" Value="True">
                        <Setter PropertyName="Background" Value="Yellow" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        <Grid.Style>
        ... your ListBoxItem contents here ...
    </Grid>
</DataTemplate>
Matt Hamilton
+2  A: 

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}}" />
Travis Heseman