Visual States in UWP

Universal Windows Platform provides us three different kind of layouts:

  1. Fluid Layout
  2. Tailored Layout
  3. Responsive Layout

Out of these three, responsive layout is more optimized to use in UWP apps. In this layout, we use visual states to tweak our UI depending upon the size of screen i.e. desktop, phone, etc.

 

In this article, we'll see how to setup visual states and develop a very basic responsive UWP app.

 

We should have Windows 10, Visual Studio 15 and UWP tools installed on our machine. I'll assume that you know the basics of VS 2015 and Windows app development.

 

Let's get started.

  • Create a new blank universal Windows app.

      http://csharpcorner.mindcrackerinc.netdna-cdn.com/UploadFile/BlogImages/07092016184551PM/uwp1.PNG

  • Open "MainPage.xaml" from solution explorer. 

      http://csharpcorner.mindcrackerinc.netdna-cdn.com/UploadFile/BlogImages/07092016184551PM/uwp2.PNG

  • Select "6" Phone (1920 x 1080) 250% scale" for preview from designer window.

      http://csharpcorner.mindcrackerinc.netdna-cdn.com/UploadFile/BlogImages/07092016184551PM/uwp3.PNG

  • Put the following code inside the main grid in the XAML code. Here we've simply created four buttons inside a StackPanel with horizontal and vertical alignment centered.

      http://csharpcorner.mindcrackerinc.netdna-cdn.com/UploadFile/BlogImages/07092016184551PM/uwp4.PNG

  • Now play with visual states. Put the following code right above the StackPanel. Here we've created a visual state inside a visual state group using a visual state manager. Focus on Line 14-19 where we've defined state triggers and setters. What we've stated here is quite simple, if the width of app windows exceeds 900 then change the layout of the StackPanel to horizontal. Always put the condition inside <VisualState.StateTriggers> and actions to be performed should go inside <VisualState.Setters>.

      http://csharpcorner.mindcrackerinc.netdna-cdn.com/UploadFile/BlogImages/07092016184551PM/uwp5.PNG

  • Build the project and test in the local machine.

      http://csharpcorner.mindcrackerinc.netdna-cdn.com/UploadFile/BlogImages/07092016184551PM/uwp6-horz.jpg 

We've covered the basics of visual states. We can do a lot of stuff with this such as changing background colors, repositioning the elements, etc. Sky is the limit. Do some create stuff and share with us.

 

If any question, please don't hesitate to ask in comments.