Creating DeviceFamily specific layouts in a Universal App

Disclaimer: This article is written based on Windows 10 Tech Preview – Build 10041. Things might change completely in the future.

In an earlier post, I showed how to use a StateTrigger to adapt parts of your UI to a specific device family (Device families are: Windows Desktop, Windows Mobile, XBox, IoT etc).

However if you want to do major differences in your UI, that’s probably not the most efficient way. Windows 10 comes with a nice trick to use completely different XAML files based on the device family you’re running on.

Let’s first create a new blank UAP project, and add the following XAML to the main <Grid> on MainPage.xaml

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
 
    <TextBlock Text="Hello Windows Desktop"
                HorizontalAlignment="Center"
                VerticalAlignment="Center"
                />        
 
</Grid>

 

When you run this on Desktop,you not surprisingly get this:

image

And also not surprising you get this on Windows Phone:

image

Now what we want to do is override the MainPage.xaml for Windows Phone and display a more correct message.

First create a new folder called DeviceFamily-[family] where [family] is ‘Mobile’:

image

Right-click this folder and choose “Add new item”

image

Pick “Xaml View” and change the name to “MainPage.xaml” This page is similar to a blank page; but is for overriding specific XAML pages – ie it doesn’t include the code behind, which you already have.

Now add the new TextBlock to this page with a more device family specific message:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
 
    <TextBlock Text="Hello Windows Phone" 
                HorizontalAlignment="Center"
                VerticalAlignment="Center" />
        
</Grid>

Because this XAML file ii in the DeviceFamily-Mobile, when running on Windows mobile, this XAML will be used instead of the default MainPage.xaml defined in the root of the project

image

So this method enables you to completely override the UI and adapt for the device family and maintain the same code-behind.

Add comment