如何根据父级的AlternateIndex设置子项的样式?

时间:2017-05-19 00:27:54

标签: wpf xaml wpf-style

我正在使用HeaderedItemsControl。每个项目都是一个3列网格,每列中都有一个Border和TextBlock。我希望每个项目中Borders的背景颜色交替。 (基本的交替行背景效果。)我试图在UserControl级别为Grid创建一个样式,它根据包含控件的AlternationIndex将背景颜色应用于其中的所有边框:

<Style TargetType="Grid" x:Key="myItemsGrid">
  <Style.Resources>
    <Style TargetType="Border">
      <Setter Property="Background" Value="Azure" />
      <Style.Triggers>
        <DataTrigger Binding="{Binding Path=AlternationIndex, RelativeSource={RelativeSource AncestorType=ItemsControl}}" Value="2">
          <Setter Property="Background" Value="{StaticResource color_LogoLight}" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </Style.Resources>
</Style>

Setter位正在工作,因为边框都是“Azure”。但是,如何正确引用AlternationIndex,以便每隔一行更改边框背景颜色。我尝试将RelativeSource指向HeaderedItemsControl和ItemsControl,但似乎都不是正确的目标。我浏览了实时视觉树,但我找不到任何可以参考的内容。

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您必须在ItemsControl项目上查找AlternationIndex,而不是在ItemsControl本身上查找!但是你必须在绑定中搜索哪种类型?例如,在ListBox中,它是一个ListBoxItem,在ItemsControl中,它是一个 ContentPresenter
不要忘记 Path=(ItemsControl.AlternationIndex) ,对于您的情况(AlternationIndex == 2),您必须在ItemsControl中将 AlternationCount 设置为至少 3 < / STRONG>!所以这段代码应该有效:

<DataTrigger Binding="{Binding Path=(ItemsControl.AlternationIndex), RelativeSource={RelativeSource AncestorType=ContentPresenter}}" Value="2">
    <Setter Property="Background" Value="{StaticResource color_LogoLight}" />
</DataTrigger>