交替背景颜色网格行不工作

时间:2015-04-29 09:48:14

标签: c# .net wpf xaml

我正在尝试在我的行上实现交替的背景颜色。 我有一个ItemsControl ItemTemplate我在Triggers Style属性Border上使用了RoyalBlue。 但我最终得到的是所有Red行,而不是<Page.Resources> <DataTemplate x:Key="myTemplate" > <Grid> <Border BorderThickness="1" CornerRadius="2" Margin="2" VerticalAlignment="Stretch" Height="20" Width="Auto"> <Border.Style> <Style TargetType="{x:Type Border}"> <Style.Triggers> <Trigger Property="ItemsControl.AlternationIndex" Value="1"> <Setter Property="Background" Value="Red" /> </Trigger> <Trigger Property="ItemsControl.AlternationIndex" Value="0"> <Setter Property="Background" Value="RoyalBlue" /> </Trigger> </Style.Triggers> </Style> </Border.Style> <Grid > <Grid.RowDefinitions> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Label Grid.Column="0" Grid.Row="0" Content="{Binding Name}"/> </Grid > </Border> </Grid> </DataTemplate> </Page.Resources> <ScrollViewer > <StackPanel > <ItemsControl ItemsSource="{Binding Path=myElements}" ItemTemplate="{StaticResource myTemplate}" AlternationCount="2"/> </StackPanel> </ScrollViewer> 。 Somene能帮忙吗?非常感谢你!

CacheConfiguration.statistics()

1 个答案:

答案 0 :(得分:3)

ItemsControl.AlternationIndex将针对ItemsControl小组(ContentPresenter)的直接子项设置,因此您需要DataTrigger使用RelativeSource绑定,因为它&#39} ; s需要放在Path=(ItemsControl.AlternationIndex)

等括号中的附加属性
<Style TargetType="{x:Type Border}">
   <Style.Triggers>
      <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ContentPresenter}}, Path=(ItemsControl.AlternationIndex)}" Value="1">
         <Setter Property="Background" Value="Red" />
      </DataTrigger>
      <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ContentPresenter}}, Path=(ItemsControl.AlternationIndex)}" Value="0">
         <Setter Property="Background" Value="RoyalBlue" />
      </DataTrigger>
   </Style.Triggers>
</Style>