如何正确使用VisualStateManager?

4

我的更改属性的代码无法正常工作,我完全不知道出了什么问题,但也许你知道。

这是一个简化的示例,可以重现错误。 这是我的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”,但什么都没有发生。
1个回答

5
将内容放置在ContentControl中,并在控件上应用VisualState,而不是在页面上应用。
此外,使用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>

在代码中,要传递内容控件而不是页面:
VisualStateManager.GoToState(contentControl, "Blue", true);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接