如何在 WinRT Hub 控件中的可见性更改时为 HubSection 设置动画

How to animate HubSection when visibility changed in WinRT Hub Control

我有一个 HubSection,它在运行时动态地 shown/hidden 使用可见性 Collapsed/Visible。我想通过扩展和收缩而不是立即显示或隐藏它来为 HubSection 设置动画。

WinRT中的动画趋向于一门学问,我还没有找到好的方法。

如果有人可以提供代码片段帮助,我将不胜感激。如果可能的话,我宁愿将它保持为 XAML,而不是将动画放在代码隐藏中。谢谢!

假设 hubsection 的可见性由视图模型的布尔值 属性 控制,通过转换器绑定,那么解决方案比我想象的要简单。即使不是这种情况,我相信您可以轻松修改下面的解决方案。

您需要引用 Behaviors SDK 才能正常工作。您可以通过转到参考>添加参考>Windows 8.1>扩展>行为 SDK 或通过在混合中打开您的项目并在您的 hubsection 上拖动 DataTriggerBehavior 来做到这一点。

必要的 xmlns 声明

xmlns:Interactivity="using:Microsoft.Xaml.Interactivity" 
xmlns:Core="using:Microsoft.Xaml.Interactions.Core"
xmlns:Media="using:Microsoft.Xaml.Interactions.Media"

<Page.Resources>
    <Converters:BoolToVisConverter x:Key="BoolToVisConverter"/>
    <Storyboard x:Name="Storyboard1">
        <DoubleAnimationUsingKeyFrames EnableDependentAnimation="True" Storyboard.TargetProperty="(FrameworkElement.Width)" Storyboard.TargetName="hubSection">
            <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
            <EasingDoubleKeyFrame KeyTime="0:0:1" Value="400"/>
        </DoubleAnimationUsingKeyFrames>
    </Storyboard>
</Page.Resources>

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Hub Header="Hub">
        <Interactivity:Interaction.Behaviors>
            <Core:DataTriggerBehavior/>
        </Interactivity:Interaction.Behaviors>
        <HubSection Header="HubSection 0">
            <DataTemplate>
                <Grid/>
            </DataTemplate>
        </HubSection>
        <HubSection x:Name="hubSection" Header="HubSection 1" Visibility="{Binding MyProperty, Converter={StaticResource BoolToVisConverter}}" Width="400" Background="#FFB02626">
            <Interactivity:Interaction.Behaviors>
                <Core:DataTriggerBehavior Binding="{Binding MyProperty}" Value="True">
                    <Media:ControlStoryboardAction Storyboard="{StaticResource Storyboard1}"/>
                </Core:DataTriggerBehavior>
            </Interactivity:Interaction.Behaviors>
            <DataTemplate>
                <Grid/>
            </DataTemplate>
        </HubSection>
    </Hub>
    <ToggleSwitch Header="ToggleSwitch" HorizontalAlignment="Left" Margin="824,249,0,0" VerticalAlignment="Top" IsOn="{Binding MyProperty, Mode=TwoWay}"/>

xaml 定义了一个具有 2 个集线器部分的集线器,一个切换开关来操纵视图模型中的布尔值 属性 和一个故事板来为第二个集线器部分设置动画。

诀窍是使用 DataTriggerBehavior 而不是 EventTriggerBehavior。

如果需要,您甚至可以直接绑定到 DataTriggerBevavior 的中心部分的可见性 属性。