XAML 系结与分镜脚本目的相关的分镜脚本属性

gcxthw6b  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(119)

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

<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。
然而,我需要将故事板存储在我的应用程序级资源中。从这里开始,故事板似乎无法将窗口作为目标来确定“From”属性。这是可以理解的,因为从<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版本,如果你把它改成本地资源版本,你就可以看到它是可行的。

93ze6v8z

93ze6v8z1#

这个例子不起作用,因为当你把你的故事板放到资源中时,它没有Window祖先。实际上,RelativeSource所做的是向后搜索元素树,等待具有AncestorType的节点出现,然后绑定它。
当放入Window.Resources时,树中会有实际的Window,并且它会正确地绑定它。当放入应用程序资源时,树中不会有Window,因为它根本没有连接到Window。
如果你真的想把你的故事板放到应用程序资源中,你应该考虑放弃绑定的想法。相反,你可以用一个裁剪器的代码来检查这个答案,我认为这就是你所需要的-https://stackoverflow.com/a/59376318/11178539

相关问题