mmv*_*sbg 9 c# wpf xaml listbox
我有一个WPF ListBox,其中包含我所拥有的特定类的项目的绑定列表.像这样的东西:
ObservableCollection<MyTable> tables = new ObservableCollection<MyTable>();
...
listTables.ItemsSource = tables;
Run Code Online (Sandbox Code Playgroud)
和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>
Run Code Online (Sandbox Code Playgroud)
一切正常.我现在要做的是对ListBox中的每个项目有不同的背景,具体取决于类的某个属性.例如,假设MyTable类有一个名为isOccupied的属性.如果为某个项目设置了这个标志,我希望它在ListBox中有一个红色背景,如果不是,那么我想让它具有绿色背景.如果属性发生更改,则背景应相应更改.
有关如何实现这一目标的任何提示?我现在正在查找有关ItemContainerStyle的一些信息,但我对此比较陌生,所以我不确定我是否遵循了正确的道路.
Fed*_*gui 15
你可以用s来实现DataTrigger
<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>
Run Code Online (Sandbox Code Playgroud)
请记住,如果您希望在运行时更改这些值,则您的数据项必须正确实现并引发属性更改通知:
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..
}
Run Code Online (Sandbox Code Playgroud)