如何在控件模板内的故事板内为TemplatedParent属性设置动画

时间:2018-01-21 12:45:27

标签: wpf xaml data-binding

<VisualState x:Name="MouseOver">
    <Storyboard>
         <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Bd" 
                                        Storyboard.TargetProperty="Fill">
              <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource 
                                        ButtonHoverBackgroundBrush}" />
          </ObjectAnimationUsingKeyFrames>
          <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Bd" 
                                         Storyboard.TargetProperty="Stroke">
               <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource 
                                                   ButtonHoverBorderBrush}" />
          </ObjectAnimationUsingKeyFrames>
          <ObjectAnimationUsingKeyFrames Duration="0" 
                                         Storyboard.TargetProperty="Foreground" 
                                         Storyboard.TargetName="ContentControl">
               <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource 
                                                   LightForegroundBrush}" />
         </ObjectAnimationUsingKeyFrames>
    </Storyboard>
</VisualState>

而不是去Storyboard.TargetName = ContentControl和Storyboard.TargetProperty = Foreground, 我想动画模板化父级的前景,内容控件只是将它的前景属性绑定到模板化父级

Foreground={TemplateBinding Foreground}

原因是当我使用此模板的控件时,我希望能够:

<Button Width="125"
        Height="30"
        Click="OnButtonClick"
        HorizontalAlignment="Left"
        VerticalAlignment="Top"
        Margin="50,54,0,0">
        <Button.Content>
            <controls:SomeCustomControl '
                             Foreground="{Binding Path=Foreground, 
                             RelativeSource={RelativeSource AncestorType=
                             {x:Type Button}}}" />                   
        </Button.Content>
</Button>

我尝试过:

<ObjectAnimationUsingKeyFrames Duration="0" Storyboard.Target="{Binding Path=Foreground, RelativeSource={RelativeSource TemplatedParent}}">
    <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource LightForegroundBrush}" />
</ObjectAnimationUsingKeyFrames>
然而,这会崩溃。 有关如何做到这一点的任何建议?提前谢谢。

1 个答案:

答案 0 :(得分:0)

同样的问题......

但可能是我们只是以错误的方式思考。

要设置样式的“内容”,但没有人知道它将是什么内容。所以“正确”的方式就是说它是你在内容中使用的控件的工作。

示例,如果将Button放入ContentControl,则Button样式处理VSM而不是围绕它的ContentControl。

这不是你问题的确切答案,但也许有些帮助可以理解为什么这不是一个选项。

编辑: 经过一些研究后我发现了这个:

Animating a TextBox.Foreground in WPF

感觉不是最好的做法,但它可以解决你的问题。