如何在用户切换 UWP 应用程序 UI 上的开关时更改故事板动画?

How to change storyboard animation when user toggles a switch on the UI for UWP Apps?

我正在开发一个 UWP 应用程序,其中有 2 个图像和一个切换开关。当切换开关处于默认(关闭状态)时,我希望显示一张图像,当用户切换开关时,我希望显示第二张图像。我的理解是,我应该使用一个网格,其中有 2 个图像堆叠在一起,并且根据切换开关的位置,我应该使用故事板并移动图像。有没有更好的方法来使用故事板的视觉状态 属性 来做这个例子?我可以使用故事板的 VisualManager 制作相同的 属性 动画,即我 UI 中的 2 个图像的过渡吗?我会学习更好的方法来使用 MVVM 和 Prism 实现此动画。

如果想在ToggleSwitch控件状态变化时切换图片,利用storyboard的视觉状态属性,可以在Grid中添加两个视觉状态来改变Image控件的Opacity,例如示例:

<Grid x:Name="grid">
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup>
            <VisualState x:Name="state1">
                <Storyboard>
                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="image1" Storyboard.TargetProperty="Opacity">
                        <DiscreteObjectKeyFrame KeyTime="0" Value="0" />
                    </ObjectAnimationUsingKeyFrames>
                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="image2" Storyboard.TargetProperty="Opacity">
                        <DiscreteObjectKeyFrame KeyTime="0" Value="1" />
                    </ObjectAnimationUsingKeyFrames>
                </Storyboard>
            </VisualState>

            <VisualState x:Name="state2">
                <Storyboard>
                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="image1" Storyboard.TargetProperty="Opacity">
                        <DiscreteObjectKeyFrame KeyTime="0" Value="1" />
                    </ObjectAnimationUsingKeyFrames>
                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="image2" Storyboard.TargetProperty="Opacity">
                        <DiscreteObjectKeyFrame KeyTime="0" Value="0" />
                    </ObjectAnimationUsingKeyFrames>
                </Storyboard>

            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="auto"/>
    </Grid.RowDefinitions>
    
    <Image Grid.Row="0" x:Name="image1" Source="Assets/11.png" Opacity="100"/>
    <Image Grid.Row="0" x:Name="image2" Source="Assets/22.png" Opacity="0"/>

    <ToggleSwitch x:Name="toggleSwitch" IsOn="False" Grid.Row="1" Toggled="toggleSwitch_Toggled">
        
    </ToggleSwitch>
</Grid>

ToggleSwitch控件的状态发生变化时,调用VisualStateManager.GoToState()进行状态切换,如下所示:

private void toggleSwitch_Toggled(object sender, RoutedEventArgs e)
{
    if(toggleSwitch.IsOn==true)
    {
        VisualStateManager.GoToState(this, "state1", false);
    }
    else
    {
        VisualStateManager.GoToState(this, "state2", false);
    }
}