如何在 WPF 中设置 DataGridRow 颜色和交替行颜色?

How to set DataGridRow Color and alternating row color in WPF?

如何将 DataGridRow 颜色设置为 DataGrid 依赖项 属性 RowBackground

<Style TargetType="{x:Type DataGrid}" x:Key="EmployeeDataGridStyle">

  <Setter Property="RowBackground" Value="White"/>
  <Setter Property="AlternatingRowBackground" Value="LightCyan"/>
  ...
</Style>

<Style TargetType="{x:Type DataGridRow}" x:Key="EmployeeDataGridRowStyle">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type DataGridRow}">
        <Border x:Name="DGR_Border"
                BorderBrush="{TemplateBinding BorderBrush}"
                BorderThickness="{TemplateBinding BorderThickness}"
                Background = { ??? //set this to the datagrid rowbackground }
                >
                ...
          <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
              <VisualState x:Name="Normal_AlternatingRow">
                <Storyboard>
                  <ColorAnimation
                    Storyboard.TargetName="DGR_Border"
                    Storyboard.TargetProperty="Background.Color"
                    Duration="0"
                    To="{ ??? // AlternatingRowBackground color that is set in the datagrid
                    >
                    ...

我正在尝试将模板中的 DataGridRow 颜色设置为 DataGrid RowBackgroundColor 属性 并尝试使用视觉状态将交替行颜色设置为AlternatingRowColor 属性 的 DataGrid。我该如何实现?

可以使用 RelativeSource 绑定来绑定到 DataGridRowBackground

Background="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=RowBackground}"

但是,ColorAnmination 中的第二个绑定 To 属性 是不可能的 by design.

You can't use dynamic resource references or data binding expressions to set Storyboard or animation property values. That's because everything inside a ControlTemplate must be thread-safe, and the timing system must FreezeStoryboard objects to make them thread-safe. A Storyboard cannot be frozen if it or its child timelines contain dynamic resource references or data binding expressions. For more information about freezing and other Freezable features, see the Freezable Objects Overview.

您可以像上面一样绑定AlternatingRowBackground动画。

Background="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=AlternatingRowBackground}"