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

时间:2010-12-17 16:24:44

标签: 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>

当故事板存储在保存故事板目标的窗口的资源中时,此故事板才有效。 'From'值正确绑定到主机Window实例的ActualWidth。

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

我想我需要能够绑定相对于动画目标的'From'值,而不是相对于故事板的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>

以下是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>

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

1 个答案:

答案 0 :(得分:1)

使用父级宽度的示例显示在:ActualWidth as value of From WPF animation

如果您想要参考父网格的宽度,您可以说

"{Binding RelativeSource={RelativeSource AncestorType={x:Type Grid}}, Path=ActualWidth}"
相关问题