列表框项目WPF,不同项目的不同背景颜色

时间:2013-11-20 15:14:27

标签: c# wpf xaml listbox

我有一个WPF ListBox,其中包含来自我所拥有的特定类的项目的绑定列表。像这样:

    ObservableCollection<MyTable> tables = new ObservableCollection<MyTable>();
...
    listTables.ItemsSource = tables;

和XAML:

<ListBox HorizontalAlignment="Left" Margin="8,10,0,0" Name="listTables" Width="153" ItemsSource="{Binding tables}" SelectionChanged="listTables_SelectionChanged" Height="501" VerticalAlignment="Top">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid Margin="1">
                    <TextBlock Grid.Column="1" Text="{Binding tableName}" />
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

一切正常。我现在要做的是对ListBox中的每个项目有不同的背景,具体取决于类的某个属性。例如,假设MyTable类有一个名为isOccupied的属性。如果为某个项目设置了这个标志,我希望它在ListBox中有一个红色背景,如果不是,那么我想让它具有绿色背景。如果属性发生变化,则背景应相应更改。

有关如何实现这一目标的任何提示?我现在正在查找有关ItemContainerStyle的一些信息,但我对此比较陌生,所以我不确定我是否遵循了正确的道路。

2 个答案:

答案 0 :(得分:15)

您可以使用DataTriggers

实现这一目标
<ListBox.ItemTemplate>
    <DataTemplate>

        <!-- Step #1: give an x:Name to this Grid -->
        <Grid Margin="1" x:Name="BackgroundGrid">
            <TextBlock Grid.Column="1" Text="{Binding tableName}" />
        </Grid>

        <!-- Step #2: create a DataTrigger that sets the Background of the Grid, depending on the value of IsOccupied property in the Model -->             
        <DataTemplate.Triggers>
            <DataTrigger Binding="{Binding IsOccupied}" Value="True">
                <Setter TargetName="BackgroundGrid" Property="Background" Value="Red"/>
            </DataTrigger>

            <DataTrigger Binding="{Binding IsOccupied}" Value="False">
                <Setter TargetName="BackgroundGrid" Property="Background" Value="Green"/>
            </DataTrigger>
        </DataTemplate.Triggers>
    </DataTemplate>
</ListBox.ItemTemplate>

请注意,如果您希望在运行时更改这些值,那么您的数据项必须正确实现并引发Property Change Notifications

public class MyTable: INotifyPropertyChanged //Side comment: revise your naming conventions, this is not a table.
{
   private bool _isOccupied;
   public bool IsOccupied
   {
       get { return _isOccupied; }
       set
       {
           _isOccupied = value;
           NotifyPropertyChange("IsOccupied");
       }
    }

    //.. Other members here..
}

答案 1 :(得分:0)

<Style TargetType="ListBox" x:Key="myListBoxStyle">
    <Style.Triggers>
        <DataTrigger Binding="{Binding SelectedItem.IsOccupied}" Value="True">
            <Setter Property="Background" Value="Red" />
        </DataTrigger>
    </Style.Triggers>
</Style>