Search code examples
xamlwindows-runtimeuwpblend

Change button style with VisualStateManager


I am working on a Universal Windows App.

I want to change the Style of my button under different states but I cant figure out (I'm new to this)

Here is my visual state group

<VisualStateGroup x:Name="StartStopTimer">
    <VisualState x:Name="Start">
    </VisualState>
    <VisualState x:Name="Stop">
        <VisualState.Setters>
        </VisualState.Setters>
    </VisualState>
</VisualStateGroup>

I have two styles setup called StartButtonStyle and StopButtonStyle.

So I want to change the buttons style to StopButonStyle in the Stop visual state and StartButtonStyle in the Start visual state.

How do I do this? I tried with record on in Expression Blend but it doesn't apply anything to my visual state.


Solution

  • Here you are:

    <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="StartStopTimer">
                <VisualState x:Name="Start">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="TestButton"
                                                       Storyboard.TargetProperty="Style">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource StartButtonStyle}">
                            </DiscreteObjectKeyFrame>
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="Stop">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="TestButton"
                                                       Storyboard.TargetProperty="Style">
                            <DiscreteObjectKeyFrame KeyTime="0"
                                                    Value="{StaticResource StopButtonStyle}">
                            </DiscreteObjectKeyFrame>
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    

    Of course you need to have defined your styles in the resources, for example in page resources.

    Please don't forget to mark my reply as an answer.