Nick's .NET Travels

Continually looking for the yellow brick road so I can catch me a wizard....

Connecting Universal Windows Platform Visual States to the StateManager

In my post State Management using BuildIt.States I made changes to elements on the page in a Universal Windows Platform (UWP) application using a StateManager. This was done to demonstrate the StateManager and this would work on any platform. However, for XAML platforms, this would normally be done via visual states. The following would describe the same states and corresponding changes to the UI.

<VisualStateManager.VisualStateGroups>
    <VisualStateGroup x:Name="MainStatesGroup">
        <VisualState x:Name="StateOne">
            <VisualState.Setters>
                <Setter Target="HelloTextBlock.(TextBlock.Text)" Value="State One" />
            </VisualState.Setters>
        </VisualState>
        <VisualState x:Name="StateTwo">
            <VisualState.Setters>
                <Setter Target="HelloTextBlock.(TextBlock.Text)" Value="State Two" />
            </VisualState.Setters>
        </VisualState>
        <VisualState x:Name="StateThree">
            <VisualState.Setters>
                <Setter Target="HelloTextBlock.(TextBlock.Text)" Value="State Three" />
            </VisualState.Setters>
        </VisualState>
        <VisualState x:Name="StateFour">
            <VisualState.Setters>
                <Setter Target="HelloTextBlock.(TextBlock.Text)" Value="State Four" />
            </VisualState.Setters>
        </VisualState>
    </VisualStateGroup>
</VisualStateManager.VisualStateGroups>

Connecting the ViewModel StateManager (which I setup in the post BuildIt.States from a ViewModel) to the visual states can be done using the VisualStateChanger class that exists in the BuildIt.Lifecycle.UWP library (https://www.nuget.org/packages/BuildIt.Lifecycle.UWP/). Again, this code is a little unrefined – I’ll be making changes to make it easier to connect up the VisualStateChanger without having to retrieve the StageGroup instance.

private VisualStateChanger<MainStates> Changer { get; set; }
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    var sm = ViewModel.StateManager;
    var grp = sm.StateGroups[typeof(MainStates)] as StateGroup<MainStates, DefaultTransition>;
    Changer = new VisualStateChanger<MainStates>(this, grp);
}

Comments are closed