簡體   English   中英

嘗試在WPF中為樣式化按鈕的背景色設置動畫時,出現InvalidOperationException

[英]InvalidOperationException when trying to animate background color of a styled button in WPF

我正在嘗試以編程方式觸發按鈕上的彩色動畫,但是當我這樣做時卻遇到了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()觸發該TryFindResource() 但是,由於該按鈕使用的是模板,因此我無法在我的XAML中正確獲取Background color屬性(如下所示)。

<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模板和屬性路徑的了解,我有點盲目地將飛鏢扔在板上。 我該如何工作?

嘗試執行此操作,完全省略Storyboard.TargetName ,並從Storyboard.TargetProperty省略Border

<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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM