如何根据其绑定值更改列表项的视觉样式?

时间:2010-06-10 14:29:35

标签: silverlight mvvm silverlight-4.0 listboxitem

我有一个列表框(这里是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>

我想要做的是让列表框中的每个项目都有3个背景中的一个(如果IsPrimary的值为真,则为绿色;如果EndDate值为空,则为橙色;如果EndDate值不为空,则为灰色。

有没有办法对列表框项进行模板化,以便它们评估绑定项以确定视图状态,或者让每个列表框项绑定到我可以为viewmodel中的每个项设置的值?

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

我认为您需要将项目Grid的背景绑定到DataContext的值,并将其传递给转换器以实现您的逻辑。像

这样的东西
<Grid Background="{Binding Converter={StaticResource myItemConverter}}">
   ...
</Grid>

转换器看起来像

public class MyItemConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var item = value as ItemModel; // [Your ListboxItem Class];
        if (item.IsPrimary)
            return System.Windows.Media.Brushes.Green;
        return item.EndDate.HasValue ? 
            System.Windows.Media.Brushes.Gray : 
            System.Windows.Media.Brushes.Orange;
    }
}