Search code examples
winrt-xamltemplate10

Visual State name in ViewModel Best Practice


I'm new to Windows Universal app programming. Decided to use Tmeplate10 to create my first app. I would like to know what is best practice to get Current Visual state name in View Model.

In code behind XAML I have been using:

 VisualState vs = AdaptiveVisualStateGroup.CurrentState;
 if (vs != null)
 {
   string actualStateName = vs.Name
 }

What is best way to get same thing in ViewModel?


Solution

  • Please don't try to mess around with the visual state in your view-model. Consider this, your view-model exists to handle the underlying data necessary for your view. This is NOT the same thing as presenting the data in your view. Your view, on the other hand, has the logic to present data - and to do it with different visual states based on certain triggers. Those triggers are visual triggers, not data triggers. For that reason, you should handle visual states in the view and the implicit code-behind of the view.

    If the data impacts the view, like if the user logs out suddenly or something, then that, too, is a property (like IsLoggedIn) in your view-model that your view uses to change the visual state. If you are trying to get a reference to the visual state in your view-model then you are sort of short circuiting the intent of MVVM.

    That being said, I am not the developer of your app, you are. And, the code you are showing is the only way to reliably get the current visual state. It is worth pointing out that more than one visual state can be active at one time across multiple visual state groups. How could you possibly run the code you provided without a direct reference of the visual state group class in your view-mode? How to get it there?

    Page.OnNavigatedTo() { ViewModel.Group = AdaptiveVisualStateGroup; } is how.

    But I hope you consider the rest of the answer.