2013-11-20 10 views
8

私には、特定のクラスのアイテムのバインドされたリストを含むWPF ListBoxがあります。このような何か:リストボックスアイテム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あなたは完全に正しいです@高額...ありがとう、私はこのサイトにいるときにもっと注意を払う必要があります。これはまったく機能しないだけでなく、計画されているエイリアンとして機能したとしても、選択したアイテムでのみ機能します。 – Sheridan

関連する問題