将Storyboard属性绑定到故事板的目标

Noe*_*edy 9 wpf xaml

我有一个故事板,它以一个元素为目标,并将其自己的一个属性绑定到另一个元素上的属性:

<Storyboard>
  <DoubleAnimation 
            Storyboard.TargetProperty="RenderTransform.X" 
            From="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=ActualWidth}" 
            To="0" 
            Duration="0:0:5"/>
 </Storyboard>
Run Code Online (Sandbox Code Playgroud)

当故事板存储在保存故事板目标的窗口的资源中时,该故事板工作."From"值正确绑定到主机Window实例的ActualWidth.

但是,我需要将故事板存储在我的应用程序级资源中.从这里开始,故事板似乎无法定位窗口以确定"发件人"属性.这是可以理解的,因为从内部来看<Application.Resources>,绑定将无法找到Window类型的"祖先".

我想我需要能够绑定相对于动画目标的'From'值,而不是相对于storyboard的DoubleAnimation.

这是可能的,如果是的话,怎么样?

以下是MainWindow.xaml示例:

<Window.Resources>
    <!--This works : Storyboard correctly sets 'From' property to 'ActualWidth' of window-->
    <Storyboard x:Key="localStoryBoard">
        <DoubleAnimation 
            Storyboard.TargetProperty="RenderTransform.X" 
            From="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=ActualWidth}" 
            To="0" 
            Duration="0:0:5"/>
    </Storyboard>
</Window.Resources>
<StackPanel>

    <Button
        RenderTransformOrigin="0,1"
        HorizontalAlignment="Left"
        Content="Click me">

        <Button.RenderTransform>
            <TranslateTransform/>
        </Button.RenderTransform>
        <Button.Triggers>
            <EventTrigger RoutedEvent="Button.Click">
                <EventTrigger.Actions>
                    <BeginStoryboard Storyboard="{StaticResource centralStoryBoard}"/>
                </EventTrigger.Actions>
            </EventTrigger> 
        </Button.Triggers>
    </Button>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

以下是app.xaml的示例:

<Application x:Class="WpfApplication3.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <!--Storyboard doesn't work at all-->
        <Storyboard x:Key="centralStoryBoard">
            <DoubleAnimation 
                Storyboard.TargetProperty="RenderTransform.X" 
                From="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=ActualWidth}" 
                To="0" 
                Duration="0:0:5"/>
        </Storyboard>
    </Application.Resources>
</Application>
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为eventtrigger引用了app.xaml版本.如果将其更改为本地资源版本,则可以看到它的工作原理.

小智 0

该示例不起作用,因为当您将故事板放入资源时,它没有 Window 祖先。而RelativeSource实际上所做的就是向后搜索元素树,等待AncestorType的节点出现,然后绑定它。

当放入 Window.Resources 时,实际的 Window 会回到树中并正确绑定它。当放入应用程序资源时,树中没有任何窗口,因为它没有连接到任何窗口。

如果您确实想将故事板放入应用程序资源中,您应该考虑放弃绑定的想法。相反,您可以使用剪刀代码查看此答案,我认为这就是您所需要的 - /sf/answers/4156342291/