2014-09-28 2 views
0

Как связать с ListBoxItemTemplate правильно в приведенном ниже примере. Я хочу показать каждый ListBoxItem, чтобы он отображался на цвет фона, указанный в теге.Переплет ListBox из ItemTemplate

<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 используется для представления связанных данных на пользовательском интерфейсе, но в вашем случае, если вы уже определили свои данные внутри ListBoxItem. Итак, наличие ItemTemplate здесь не имеет смысла. Кроме того, вы можете просто установить Background на ListBoxItem itelf, а не устанавливать его в тег.

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

Когда я применяю тему, это не работает. Но корректировка then ItemContainerStyle