2015-02-09 22 views
0

我有一个ListBox,我想它有根据交替指数2组完全不同的数据模板的样式。我看过很多关于如何根据索引更改背景颜色但不更改每个索引样式的教程。这是迄今为止我所拥有的。列表框ContentControl中有两个数据模板和触发器alternationindex,XAML

定义的模板:

<UserControl.Resources> 
    <DataTemplate x:Key="ItemLeft" > 
     <Border Background="Blue" Height="10"> 
      <!-- Define Left Style --> 

     </Border> 
    </DataTemplate> 
    <DataTemplate x:Key="ItemRight"> 
     <Border Background="Red" Height="10"> 
      <!-- Define Right Style --> 

     </Border> 
    </DataTemplate> 
</UserControl.Resources> 

我已经删除了数据模板代码,使其更易于阅读。这比边框颜色要多得多。

列表框:

 <ListBox Name="StatusListBox" AlternationCount="2"> 
      <ListBox.ItemTemplate> 
       <DataTemplate> 
        <ContentControl Content="{Binding}"> 
         <ContentControl.Style> 
          <Style TargetType="{x:Type ContentControl}"> 
           <Setter Property="ContentTemplate" Value="{StaticResource ItemLeft}"/> 
           <Style.Triggers> 
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ContentPresenter}}, Path=(ListBox.AlternationIndex)}" Value="1"> 
             <Setter Property="ContentTemplate" Value="{StaticResource ItemRight}"/> 
            </DataTrigger> 
           </Style.Triggers> 
          </Style> 
         </ContentControl.Style> 
        </ContentControl> 
       </DataTemplate> 
      </ListBox.ItemTemplate> 
     </ListBox> 

该代码没有设置内容控制得当。我要么做错了,要么错过了一步。我是使用WPF的新手,我发现它大部分非常直观,但我迷失在这里。我想尝试将其包含到XAML代码中。

感谢

回答

3

您可以直接设置ItemContainerStyle,而不是造型在ItemTemplate一个ContentPresenter的。该风格将有一个Trigger而不是DataTrigger为AlternationIndex:

<ListBox AlternationCount="2"> 
    <ListBox.ItemContainerStyle> 
     <Style TargetType="ListBoxItem"> 
      <Setter Property="ContentTemplate" Value="{StaticResource ItemLeft}"/> 
      <Style.Triggers> 
       <Trigger Property="ItemsControl.AlternationIndex" Value="1"> 
        <Setter Property="ContentTemplate" 
          Value="{StaticResource ItemRight}"/> 
       </Trigger> 
      </Style.Triggers> 
     </Style> 
    </ListBox.ItemContainerStyle> 
</ListBox> 
+0

我甚至没有看到有关aternationindex +1部分 – 2015-02-09 18:57:04