WPF动画的DataGridRow背景颜色从透明变为“当前”(通过“触发器”设置当前值)

use*_*007 1 wpf

DataGridRow BackgroundColor根据触发LogError值设置为绿色或红色。

我想为新添加的行设置透明度。

这很好用:

From="Transparent" To="Red"
Run Code Online (Sandbox Code Playgroud)

但是我想要的颜色是使用Style设置的当前颜色。它并不总是红色,也可能是绿色。

这不起作用:

From="Transparent" To="{TemplateBinding DataGridRow.Background}"
Run Code Online (Sandbox Code Playgroud)

要么

From="Transparent" To="{Binding RelativeSource={RelativeSource Self}, Path=Backgound}"
Run Code Online (Sandbox Code Playgroud)

码:

<DataGrid.Resources>
  <Style TargetType="{x:Type DataGridRow}">
    <Setter Property = "Background" Value="LimeGreen"/>
    <Style.Triggers>
      <DataTrigger Binding="{Binding LogMessage}" Value="Exception has occured">
        <Setter Property = "Background" Value="Red"/>
      </DataTrigger>
    </Style.Triggers>
  </Style>
</DataGrid.Resources>          
<DataGrid.RowStyle>
  <Style TargetType="DataGridRow">
    <Style.Triggers>
      <EventTrigger RoutedEvent="Loaded">
        <BeginStoryboard>
          <Storyboard>
            <ColorAnimation
                Storyboard.TargetProperty="(DataGridRow.Background).(SolidColorBrush.Color)" 
                Duration="00:00:03" 
                From="Transparent"
                To="{TemplateBinding DataGridRow.Background}"/>
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Style.Triggers>
  </Style>
</DataGrid.RowStyle>
Run Code Online (Sandbox Code Playgroud)

错误信息: Cannot freeze this Storyboard timeline tree for use across threads.

Roh*_*ats 5

您的XAML代码中几乎没有问题。

首先,您在DataGrid的资源部分下指定了默认样式,然后提供了自己的样式,它将覆盖默认样式。您应该定义新样式并将其BasedOnDP 设置为引用默认样式。但就您而言,我看不到any use of defining separate style just for trigger

其次,您希望动画从Transparent样式选择的颜色变成LimeGreen或Red(取决于触发器)。因此,您不应To在动画中设置值,因为它会自动拾取。

这将按您的意愿工作-

   <DataGrid>
      <DataGrid.Resources>
          <Style TargetType="{x:Type DataGridRow}">
              <Setter Property ="Background" Value="LimeGreen"/>
              <Style.Triggers>
                 <DataTrigger Binding="{Binding LogMessage}"
                                        Value="Exception has occured">
                     <Setter Property = "Background" Value="Red"/>
                 </DataTrigger>
                 <EventTrigger RoutedEvent="Loaded">
                     <BeginStoryboard>
                         <Storyboard>
                             <ColorAnimation Storyboard.TargetProperty=
                              "(DataGridRow.Background).(SolidColorBrush.Color)" 
                                             Duration="00:00:03" 
                                             From="Transparent"/>
                         </Storyboard>
                     </BeginStoryboard>
                 </EventTrigger>
               </Style.Triggers>
            </Style>
        </DataGrid.Resources>
   </DataGrid>
Run Code Online (Sandbox Code Playgroud)