2014-09-28 63 views
0

如何在以下示例中正確綁定ListBoxItemTemplate。我想將每個ListBoxItem顯示爲在標籤中指定的背景顏色。來自ItemTemplate的ListBox綁定

<ListBox> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <Border Background="{Binding Path=Tag, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}"> 
       <TextBlock Text="{Binding}"/> 
      </Border> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
    <ListBox.Items> 
     <ListBoxItem Content="1" Tag="Blue" /> 
     <ListBoxItem Content="2" Tag="Green"/> 
     <ListBoxItem Content="3" Tag="Red"/> 
    </ListBox.Items> 
</ListBox> 

回答

0

你需要ItemContainerStyle,而不是ItemTemplate

<ListBox> 
    <ListBox.ItemContainerStyle> 
     <Style TargetType="ListBoxItem"> 
      <Setter Property="Background" Value="{Binding Tag, 
            RelativeSource={RelativeSource Self}}"/> 
     </Style> 
    </ListBox.ItemContainerStyle> 
    <ListBox.Items> 
     <ListBoxItem Content="1" Tag="Blue" /> 
     <ListBoxItem Content="2" Tag="Green"/> 
     <ListBoxItem Content="3" Tag="Red"/> 
    </ListBox.Items> 
</ListBox> 

的ItemTemplate用來表示對UI數據綁定,但在你的情況,你已經定義裏面ListBoxItem的數據。因此,ItemTemplate在這裏沒有意義。此外,您可以簡單地將ListBoxItem上的Background設置爲自己,而不是將其設置在Tag中。

<ListBox> 
    <ListBox.Items> 
     <ListBoxItem Content="1" Background="Blue" /> 
     <ListBoxItem Content="2" Background="Green"/> 
     <ListBoxItem Content="3" Background="Red"/> 
    </ListBox.Items> 
</ListBox> 
+0

當我有一個主題應用上述不起作用仍然。但調整然後ItemContainerStyle