WPF-将故事板放入资源字典

时间:2018-11-05 11:02:18

标签: c# wpf xaml material-design

我的MainWindow.xaml中有这个故事板,基本上可以隐藏和显示网格。

<Storyboard x:Key="MenuOpen">
    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Width)" Storyboard.TargetName="GridMenu">
        <EasingDoubleKeyFrame KeyTime="0" Value="50"/>
        <EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="150"/>
    </DoubleAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Key="MenuClose">
    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Width)" Storyboard.TargetName="GridMenu">
        <EasingDoubleKeyFrame KeyTime="0" Value="150"/>
        <EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="50"/>
    </DoubleAnimationUsingKeyFrames>
</Storyboard>

<Window.Triggers>
    <EventTrigger RoutedEvent="ButtonBase.Click" SourceName="btnOpenMenu">
        <BeginStoryboard Storyboard="{StaticResource MenuOpen}"/>
    </EventTrigger>
    <EventTrigger RoutedEvent="ButtonBase.Click" SourceName="btnCloseMenu">
        <BeginStoryboard Storyboard="{StaticResource MenuClose}"/>
    </EventTrigger>
</Window.Triggers>

我想要的是将整个代码放入资源字典中。我已经把它的很大一部分放在我创建的字典中,但是接下来的那部分我不能。我尝试了许多不同的方法,但是似乎都没有用。

<Window.Triggers>
    <EventTrigger RoutedEvent="ButtonBase.Click" SourceName="btnOpenMenu">
        <BeginStoryboard Storyboard="{StaticResource MenuOpen}"/>
    </EventTrigger>
    <EventTrigger RoutedEvent="ButtonBase.Click" SourceName="btnCloseMenu">
        <BeginStoryboard Storyboard="{StaticResource MenuClose}"/>
    </EventTrigger>
</Window.Triggers>

是否可以将触发器放入资源字典中,还是应该使用其他方式?如果可能的话,使这项工作正确的方法是什么?

致谢。

1 个答案:

答案 0 :(得分:0)

您可以将EventTriggers定义为如下资源:

<Storyboard x:Key="MenuOpen">
    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Width)" Storyboard.TargetName="GridMenu">
        <EasingDoubleKeyFrame KeyTime="0" Value="50"/>
        <EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="150"/>
    </DoubleAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Key="MenuClose">
    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Width)" Storyboard.TargetName="GridMenu">
        <EasingDoubleKeyFrame KeyTime="0" Value="150"/>
        <EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="50"/>
    </DoubleAnimationUsingKeyFrames>
</Storyboard>

<EventTrigger x:Key="et" RoutedEvent="ButtonBase.Click" SourceName="btnOpenMenu">
    <BeginStoryboard Storyboard="{StaticResource MenuOpen}"/>
</EventTrigger>

<EventTrigger x:Key="et2" RoutedEvent="ButtonBase.Click" SourceName="btnCloseMenu">
    <BeginStoryboard Storyboard="{StaticResource MenuClose}"/>
</EventTrigger>

...并在这样的窗口中引用它们:

<Window.Triggers>
    <StaticResource ResourceKey="et" />
    <StaticResource ResourceKey="et2" />
</Window.Triggers>