R – Dynamically setting background colour of a Silverlight control (Listbox)

silverlight

How do I set the background colour of items in a list box dynamically? i.e. there is some property on my business object that I'm binding too, so based on some business rules I want the background colour to be different?

        <ListBox Background="Red">
      <ListBox.ItemContainerStyle>
          <Style TargetType="ListBoxItem">
              <Setter Property="Background" Value="Red"/>
          </Style>
      </ListBox.ItemContainerStyle>
 <ListBox.ItemTemplate>
      <DataTemplate>
                    <StackPanel Orientation="Horizontal"
                                Margin="5">
                        <TextBlock VerticalAlignment="Bottom"
                                   FontFamily="Comic Sans MS"
                                   FontSize="12"
                                   Width="70"
                                   Text="{Binding Name}" />
                        <TextBlock VerticalAlignment="Bottom"
                                   FontFamily="Comic Sans MS"
                                   FontSize="12"
                                   Width="70"
                                   Text="{Binding Age}" />
                     </StackPanel>
                </DataTemplate>
        </ListBox.ItemTemplate>
      </ListBox>

EDIT: It says here

In Silverlight, you must add x:Key
attributes to your custom styles and
reference them as static resources.
Silverlight does not support implicit
styles applied using the TargetType
attribute value.

Does this impact my approach?

Best Answer

Ok - if you need custom logic to determine the background then I would look into building a simple IValueConverter class. You just need to implement the IValueConverter interface and, in its Convert method, change the supplied value into a Brush.

Here's a quick post from Sahil Malik that describes IValueConverters - it might help:

http://blah.winsmarts.com/2007-3-WPF__DataBinding_to_Calculated_Values--The_IValueConverter_interface.aspx

Related Topic