尝试在WPF

时间:2016-11-21 23:09:06

标签: c# wpf xaml

我正在尝试以编程方式触发按钮上的彩色动画,但是当我这样做时会获得System.InvalidOperationException。它似乎无法解析TargetProperty,因为我使用模板/内容展示器设置了按钮的样式。

我以这种方式设置<Button>的原因是强制样式保持一致(并避免默认的蓝色悬停效果)。我还有一个DataTrigger,只要它显示(即可见),它就会激活该按钮的背景颜色。这是完整的<Style>定义:

<Style x:Key="PopUnder" TargetType="Button">
  <Setter Property="Foreground" Value="Black" />
  <Setter Property="FontSize" Value="34" />
  <Setter Property="FontWeight" Value="SemiBold" />
  <Setter Property="OverridesDefaultStyle" Value="True" />
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="Button">
        <Border Name="Border" Background="White" BorderBrush="Red" BorderThickness="0,1,0,1">
          <TextBlock TextWrapping="Wrap" TextAlignment="Center" VerticalAlignment="Center" LineStackingStrategy="BlockLineHeight" LineHeight="40" Text="{TemplateBinding Content}" />
        </Border>
        <ControlTemplate.Triggers>
          <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Visibility}" Value="Visible">
            <DataTrigger.EnterActions>
              <BeginStoryboard>
                <Storyboard>
                  <ColorAnimationUsingKeyFrames Storyboard.TargetName="Border" Storyboard.TargetProperty="(Background).(SolidColorBrush.Color)" RepeatBehavior="Forever">
                    <LinearColorKeyFrame Value="White" KeyTime="0:0:0" />
                    <LinearColorKeyFrame Value="LightCoral" KeyTime="0:0:1" />
                    <LinearColorKeyFrame Value="White" KeyTime="0:0:2" />
                  </ColorAnimationUsingKeyFrames>
                </Storyboard>
              </BeginStoryboard>
            </DataTrigger.EnterActions>
          </DataTrigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

但我也希望能够从代码中触发同一个按钮上的不同动画。所以我在其他地方(在样式定义之外)定义了一个单独的<Storyboard>,我使用TryFindResource() ... Begin()触发。但是,因为按钮使用的是模板,所以我无法在我的XAML(下面)中正确解析背景颜色属性。

<Storyboard x:Key="StatusGood" Completed="AnimationStatusGood_Completed">
  <ColorAnimationUsingKeyFrames Storyboard.TargetName="PopUnderMessage" Storyboard.TargetProperty="(Border).(Background).(SolidColorBrush.Color)">
      <LinearColorKeyFrame Value="LightGreen" KeyTime="0:0:0" />
      <LinearColorKeyFrame Value="White" KeyTime="0:0:1" />
  </ColorAnimationUsingKeyFrames>
</Storyboard>

我在这里为Storyboard.TargetProperty属性尝试了几个不同的值:

  • (背景)。(SolidColorBrush.Color)
  • (边界)。(背景)。(SolidColorBrush.Color)
  • (Border.Background)。(SolidColorBrush.Color)

但是所有这些都会对同一个异常产生不同的变化。我承认我会盲目地在飞机板上投掷飞镖,因为我对XAML模板和属性路径的了解不足。我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:0)

尝试此操作,完全省略Storyboard.TargetName,并忽略Border中的Storyboard.TargetProperty

<Storyboard x:Key="StatusGood" Completed="AnimationStatusGood_Completed">
    <ColorAnimationUsingKeyFrames
        Storyboard.TargetProperty="(Background).(SolidColorBrush.Color)">
        <LinearColorKeyFrame Value="LightGreen" KeyTime="0:0:0" />
        <LinearColorKeyFrame Value="White" KeyTime="0:0:1" />
    </ColorAnimationUsingKeyFrames>
</Storyboard>

为样式化按钮添加名称:

<Button
    x:Name="button"
    Content="Hello, world!"
    Style="{StaticResource PopUnder}" Click="ButtonBase_OnClick" />

要激活故事板:

private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
    Storyboard storyboard = (Storyboard)this.TryFindResource("StatusGood");
    Border border = FindVisualChild<Border>(button, "Border");
    storyboard.Begin(border);
}

供参考,FindVisualChild辅助函数:

private static T FindVisualChild<T>(
    DependencyObject parent,
    string name = null)
    where T : DependencyObject
{
    if (parent != null)
    {
        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < childrenCount; i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(parent, i);
            T candidate = child as T;
            if (candidate != null)
            {
                if (name == null)
                {
                    return candidate;
                }

                FrameworkElement element = candidate as FrameworkElement;
                if (name == element?.Name)
                {
                    return candidate;
                }
            }

            T childOfChild = FindVisualChild<T>(child, name);
            if (childOfChild != null)
            {
                return childOfChild;
            }
        }
    }

    return default(T);
}