【发布时间】:2010-12-17 16:24:43
【问题描述】:
我有一个故事板,它以一个元素为目标,并将它自己的一个属性绑定到另一个元素上的一个属性:
<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 版本。如果你把它改成本地资源版本,你可以看到它的工作原理。
【问题讨论】:
-
这是一个很好的问题。此类问题的信息很难获得,因此希望有人可以回答。如果有帮助的话,我注意到它也可以在合并的 ResourceDictionary 中工作