c# - 如何检查 DataTemplate 中的 AlternationCount?

标签 c# wpf datagrid

我为我的 DataGrid 创建了一个 DataTemplate:

 <DataTemplate x:Key="MyDataTemplate">
     <Label>Test</Label>
  </DataTemplate>

DataTemplate 将用于 DataGridTemplateColumnDataGrid 有一个 AlternationCount = 2 属性。

我想检查我的 DataTemplate 中的当前 AlternationCount 以根据 AlternationCount 设置内容。我如何请求 AlternationCount

更新 1:

我使用以下代码尝试了 Sheridan 的建议:

<Style x:Key="MyStyle" TargetType="Label">
  <Style.Triggers>
    <Trigger Property="ItemsControl.AlternationIndex" Value="0">
      <Setter Property="Background" Value="Red" />
    </Trigger>
    <Trigger Property="ItemsControl.AlternationIndex" Value="1">
      <Setter Property="Background" Value="Blue" />
    </Trigger>
  </Style.Triggers>
</Style>

在我的 DataTemplate 中使用这种样式,如下所示:

<DataTemplate x:Key="MyDataTemplate">
  <Label x:Name="MyLabel" Style={StaticResource MyStyle}">Test</Label>
</DataTemplate>

但不幸的是,只出现了红色背景。在我看来,AlternationIndex 始终为 0。我在这里缺少什么?

最佳答案

可以访问 AlternationCount attached property ,尽管我认为您实际上需要 AlternationIndex attached property反而。本质上,您可以在 Trigger 的 XAML 中访问此附加属性的值,如下所示:

<Style>
    <Style.Triggers>
        <Trigger Property="ItemsControl.AlternationIndex" Value="0">
            <Setter Property="Foreground" Value="Green" />
        </Trigger>
        <Trigger Property="ItemsControl.AlternationIndex" Value="1">
            <Setter Property="Foreground" Value="Red" />
        </Trigger>
    </Style.Triggers>
</Style>

更新>>>

StyleTargetType 不应设置为Label。它应该设置为数据的容器,例如。 ComboBoxItem、ListBoxItem 等。在您的情况下,您应该将 Style TargetType 设置为 DataGridRow:

<Style TargetType="{x:Type DataGridRow}">
    <Style.Triggers>
        <Trigger Property="ItemsControl.AlternationIndex" Value="0">
            <Setter Property="Background" Value="Green" />
        </Trigger>
        <Trigger Property="ItemsControl.AlternationIndex" Value="1">
            <Setter Property="Background" Value="Red" />
        </Trigger>
    </Style.Triggers>
</Style>

如果您设置Stylex:Key 值,假设您将其命名为RowStyle,那么您可以设置那个Style 作为 DataGrid.RowStyle 属性值:

<DataGrid RowStyle="{StaticResource RowStyle}" ... />

如果您没有设置Stylex:Key 值并且它在DataGrid 的范围内,那么它将隐式应用。

关于c# - 如何检查 DataTemplate 中的 AlternationCount?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23786842/

相关文章:

wpf - 数据网格复选框自动化

c# - 函数在同步调用时有效,但在异步调用时无效

javascript - 如何在 Javascript 中检查 ASP.NET C# Request.IsAuthenticated?

c# - 如何设置一个像素宽度的网格线(WPF DataGrid)?

c# - 从ViewModel中选择 ListView 中的所有项目

wpf - 将弹出窗口的宽度绑定(bind)到其他控件的宽度,并带有一些边距

wpf - 将 wpf 文本 block 滚动到末尾

c# - 当现有的 Excel 文件在桌面上**打开**时,是否可以写入该文件?

c# - EntityFramework 外键作为具有流畅 API 的主键

wpf - 在后面的代码中查找类型的默认样式