2015-04-29 79 views
1

我想在我的行上實現交替的背景顏色。 我有ItemsControlItemTemplate其中我TriggersStyleBorder財產。 但我最終與所有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> 
+0

Mayby [這個例子](https://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.alternationindex%28v=vs.110%29.aspx)可以幫助你。他們使用'Setter'和'Converter'代替觸發器。 – azt

回答

3

ItemsControl.AlternationIndex將設置對ItemsControl面板(ContentPresenter)的直接孩子,所以你需要使用DataTriggerRelativeSource約束力,因爲它是一個附加屬性,你需要把括號像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>