2014-09-28 68 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