在XAML中将属性绑定到Storyboard值

时间:2015-01-08 18:27:38

标签: wpf xaml binding storyboard windows-store-apps

我有一个Storyboard动画,如下所示:

<Grid Name="Choice" VerticalAlignment="Stretch" Width="400">
    <Interactivity:Interaction.Behaviors>
        <Core:EventTriggerBehavior EventName="Tapped">
            <Media:ControlStoryboardAction>
                <Media:ControlStoryboardAction.Storyboard>
                    <Storyboard x:Name="Animation">
                        <DoubleAnimationUsingKeyFrames EnableDependentAnimation="True" Storyboard.TargetProperty="(FrameworkElement.Width)" Storyboard.TargetName="Choice">
                            <EasingDoubleKeyFrame KeyTime="0" Value="{Binding Path=InitialWidth}"/>
                            <EasingDoubleKeyFrame KeyTime="0:0:1" Value="{Binding Path=FinalWidth}" />
                        </DoubleAnimationUsingKeyFrames>
                    </Storyboard>
                </Media:ControlStoryboardAction.Storyboard>
            </Media:ControlStoryboardAction>
        </Core:EventTriggerBehavior>
    </Interactivity:Interaction.Behaviors>
    <Image HorizontalAlignment="Center" VerticalAlignment="Center" Source="{Binding Path=Image}" Stretch="UniformToFill" />
</Grid>

我在属性InitialWidthFinalWidth中设置的初始值似乎是正确的,但如果我稍后更改,则它们不会更新,而是0。我在某处读到,在运行时无法将属性绑定到Storyboard值,但我没有找到任何正式文档说明。
我的问题是,我可以将属性绑定到Storyboard值吗?如果是这样,我需要改变什么?

1 个答案:

答案 0 :(得分:1)

我无法对此进行测试,因此请将其作为“可能有效”的建议。我们的想法是在您的页面资源中创建一个“代理”对象,然后使用StaticResource绑定来引用它。

代理只是一个DependencyObject,它包含您对绑定感兴趣的属性:

public class ProxyObject : DependencyObject
{
    public double InitialWidth
    {
        get { return (double)GetValue(InitialWidthProperty); }
        set { SetValue(InitialWidthProperty, value); }
    }
    public static readonly DependencyProperty InitialWidthProperty =
        DependencyProperty.Register("InitialWidth", typeof(double), typeof(ProxyObject), new PropertyMetadata(0));

    public double FinalWidth
    {
        get { return (double)GetValue(FinalWidthProperty); }
        set { SetValue(FinalWidthProperty, value); }
    }
    public static readonly DependencyProperty FinalWidthProperty =
        DependencyProperty.Register("FinalWidth", typeof(double), typeof(ProxyObject), new PropertyMetadata(0));
}

现在在页面资源中实例化它,并绑定到您的视图模型:

<Grid Name="Choice">
    <Grid.Resources>
        <ResourceDictionary>
            <local:ProxyObject x:Name="proxy"
                InitialWidth="{Binding InitialWidth}" FinalWidth="{Binding FinalWidth}" />
        </ResourceDictionary>
    </Grid.Resources>
    ...
</Grid>

然后,您可以将其作为时间轴元素中的静态资源引用:

<EasingDoubleKeyFrame KeyTime="0" 
    Value="{Binding Source="{StaticResource proxy},Path=InitialWidth}" />
<EasingDoubleKeyFrame KeyTime="0:0:1" 
    Value="{Binding Source="{StaticResource proxy},Path=InitialWidth}" />

我已成功使用Silverlight中的类似内容(控件模板中的可视状态故事板),但我不确定它是否适用于您的场景。