Set background color property dynamically RRS feed

  • Question

  • I am using MVVM pattern in my WPF application.

    I have a collection of objects.Based upon a property of each collection object,I need to set the background color.

    I need to loop through the collection and decide upon the background color.

    i.e,for the same property value  background color should be the same.

    How can I achieve this?

    Thursday, April 26, 2012 7:55 AM


  • Hi,

    Lets says your collection type is CustomObj.

    In the CustomObj class I would add a new public property

    public int ColorVal {get; set;}

    then when you iterate the collection I would change the value of each CustomObj object colorVal property to a different int

    1 = red, 2 = green, 3 - orange (etc)  

    Then in your view create styles for all the controls that inheirt from this collection and have a trigger in that style that binds to ColorVal property and changes background color based on the ColorVal property's value

    <Style TargetType="{x:Type DataGridRow}"> <Style.Triggers>

    <Trigger Property="{Binding Path=ColorVal}" Value="1">

    <Setter Property="Background" Value="Red"/>

    </Trigger> <Trigger Property="{Binding Path=ColorVal}" Value="2">                         <Setter Property="Background" Value="Green"/> 


     <Trigger Property="{Binding Path=ColorVal}" Value="3">                        
          <Setter Property="Background" Value="Orange"/> 


    </Style.Triggers> </Style>

    • Marked as answer by Kee Poppy Thursday, May 3, 2012 7:53 AM
    Thursday, April 26, 2012 8:39 AM