2013-11-20 53 views
8

我有一个WPF列表框,其中包含一个来自特定类的项目的绑定列表。事情是这样的:列表框项目WPF,不同项目的不同背景颜色

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的一些信息,但是我对此比较陌生,所以我不确定是否遵循正确的路径。

回答

13

可以实现,使用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.. 
} 
+0

你可能还有eran的旧+1。 ;) – Sheridan

+0

这非常有帮助,就像一个魅力。非常感谢你! – mmvsbg

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> 
+0

+1现在有一个正确的答案......对解释(对于那些需要的用户)有一点点解释,但一个正确的答案都是一样的。 – Sheridan

+0

@Sheridan你确定这将实现OP的要求吗?检查我的答案 –

+0

+0您完全正确@HighCore ...谢谢,我需要更多的关注,当我在这个网站上。这不仅不会起作用,而且即使它按照eran计划工作,它也只会在选定的项目上起作用。 – Sheridan