开发者

In a style, how can I refer to the element on which the style is applied?

开发者 https://www.devze.com 2022-12-15 19:24 出处:网络
In a style, how can I refer to the element on which the style is applied ? For instance, in the style I define a RenderTransform, and I would like to add an animation on the RenderTransform :

In a style, how can I refer to the element on which the style is applied ? For instance, in the style I define a RenderTransform, and I would like to add an animation on the RenderTransform :

    <Style x:Key="myStyle" TargetType="{x:Type FrameworkElement}">

        <Setter Property="RenderTransform">
            <Setter.Value>
                <ScaleTransform />
            </Setter.Value>
        </Setter>

        <Setter Property="RenderTransformOrigin"
                Value="0.5, 0.5" />

        <Style.Triggers>
            <EventTrigger RoutedEvent="MouseDown">
              开发者_开发技巧  <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Duration="0:0:0.2"
                                         From="1"
                                         To="1.2"
                                         AutoReverse="True"
                                         Storyboard.Target="{Binding RenderTransform}"
                                         Storyboard.TargetProperty="(ScaleTransform.ScaleX)" />
                        <DoubleAnimation Duration="0:0:0.2"
                                         From="1"
                                         To="1.2"
                                         AutoReverse="True"
                                         Storyboard.Target="{Binding RenderTransform}"
                                         Storyboard.TargetProperty="(ScaleTransform.ScaleY)" />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Style.Triggers>

    </Style>

Of course, the code above doesn't work, because {Binding RenderTransform} uses the DataContext as the source. I tried to specify the RelativeSource with FindAncestor mode, but it can't find a FrameworkElement parent (probably because the storyboard is not part of the visual tree).

Is there a way to bind to a property of the element on which the style is applied ?


A Storyboard in a Style automatically targets the element to which the style is being applied So you can just leave out the Storyboard.Target altogether. However you will need to change your TargetProperty to navigate from the element itself rather than from the RenderTransform property. The following therefore works for me:

<DoubleAnimation Duration="0:0:0.2"
                 From="1"
                 To="1.2"
                 AutoReverse="True"
                 Storyboard.TargetProperty="RenderTransform.ScaleX" />
0

精彩评论

暂无评论...
验证码 换一张
取 消