如何在以下示例中正确绑定ListBox
ItemTemplate
。我希望每个ListBoxItem
都显示在标记中指定的背景颜色上。
<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 :(得分: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上设置背景,而不是在标记 中设置它。
<ListBox>
<ListBox.Items>
<ListBoxItem Content="1" Background="Blue" />
<ListBoxItem Content="2" Background="Green"/>
<ListBoxItem Content="3" Background="Red"/>
</ListBox.Items>
</ListBox>