How do I change the visual style of a listitem based on its bound value?

Posted by Rodd on Stack Overflow See other posts from Stack Overflow or by Rodd
Published on 2010-06-10T14:29:35Z Indexed on 2010/06/10 17:22 UTC
Read the original article Hit count: 222

Filed under:
|
|

I have a listbox (here's the xaml):

            <ListBox MinWidth="300" ItemsSource="{Binding Relationships, Mode=OneWay}" 
        SelectedItem="{Binding SelectedRelationship, Mode=TwoWay}" SelectionMode="Single" 
        HorizontalAlignment="Left" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>
                        <Grid.RowDefinitions>
                            <RowDefinition/>
                            <RowDefinition/>
                            <RowDefinition/>
                            <RowDefinition/>
                            <RowDefinition/>
                            <RowDefinition/>
                        </Grid.RowDefinitions>
                        <CheckBox IsChecked = "{Binding IsPrimary}" IsHitTestVisible="False" />
                        <StackPanel Orientation="Horizontal" Grid.Column="1">
                            <TextBlock Text="{Binding RelationshipType}"  FontWeight="Bold"  Margin="0,0,5,0" />
                            <TextBlock Text="{Binding Status}"  FontStyle="Italic" />                           
                        </StackPanel>
                        <TextBlock Text="{Binding UnitName}" Grid.Row="1" Grid.Column="1" />
                        <TextBlock Text="{Binding StartDate, Converter={StaticResource DateConverter}}" Grid.Row="2" Grid.Column="1"/>
                        <TextBlock Text="{Binding RetireDate}" Grid.Row="3" Grid.Column="1" />
                        <TextBlock Text="{Binding EndDate}" Grid.Row="4" Grid.Column="1" />
                        <TextBlock Text="{Binding ReasonForLeaving}" Grid.Row="5" Grid.Column="1" />
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

What I want to do is have each item in the listbox have one of 3 backgrounds (green if the value of IsPrimary = true, Orange if the EndDate value is empty and grey if the EndDate value is not empty.

Is there a way to template the listbox items so that they evaluate bound items to determine a view state or to have each listbox item bind to a value that I can set for each item in my viewmodel?

Thanks for your help.

© Stack Overflow or respective owner

Related posts about mvvm

Related posts about silverlight-4.0