如何正确使用VisualStateManager

本文关键字:VisualStateManager 何正确 | 更新日期: 2023-09-27 17:57:49

我的更改属性的代码不起作用,我完全不知道出了什么问题,但也许你知道。

下面是我的代码的一个简化示例,它再现了错误。这是我的Xaml代码:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Button x:Name="MyButton"
            Height="100" 
            Width="300" 
            Content="Click" 
            FontSize="40" 
            FontWeight="Bold" 
            VerticalAlignment="Center" 
            HorizontalAlignment="Center" 
            Background="Red" Click="MyButton_Click"/>
</Grid>
<VisualStateManager.VisualStateGroups>
    <VisualStateGroup>
        <VisualState x:Name="Blue">
            <Storyboard>
                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="MyButton"
                                               Storyboard.TargetProperty="Background">
                    <DiscreteObjectKeyFrame KeyTime="0" Value="Aqua"/>
                </ObjectAnimationUsingKeyFrames>
            </Storyboard>
        </VisualState>
    </VisualStateGroup>
</VisualStateManager.VisualStateGroups>

这就是背后的代码:

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }
    private void MyButton_Click(object sender, RoutedEventArgs e)
    {
        VisualStateManager.GoToState(this, "Blue", true);
    }
}

理论上,单击按钮时应该将按钮颜色更改为"Aqua",但什么也没发生。

如何正确使用VisualStateManager

将内容放在ContentControl中,并在控件上应用VisualState,而不是在Page上。

此外,请使用ColorAnimation设置按钮颜色的动画,而不是使用ObjectAnimation

<ContentControl x:Name="contentControl">
    <ContentControl.Template>
        <ControlTemplate>
            <Grid
              Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
                <Button x:Name="MyButton"
                        Height="100" 
                        Width="300" 
                        Content="Click" 
                        FontSize="40" 
                        FontWeight="Bold" 
                        VerticalAlignment="Center" 
                        HorizontalAlignment="Center" 
                        Background="Red" Click="Button_Click"/>
                <VisualStateManager.VisualStateGroups>
                    <VisualStateGroup x:Name="CustomGroups">
                        <VisualState x:Name="Blue">
                            <Storyboard>
                                <ColorAnimation Storyboard.TargetName="MyButton" 
                                    Storyboard.TargetProperty="Background.Color"
                                    To="Aqua"/>
                            </Storyboard>
                        </VisualState>
                    </VisualStateGroup>
                </VisualStateManager.VisualStateGroups>
            </Grid>
        </ControlTemplate>
    </ContentControl.Template>
</ContentControl>

在代码隐藏中,传递内容控制而不是Page:

VisualStateManager.GoToState(contentControl, "Blue", true);
相关文章:
  • 没有找到相关文章