UWP Apps with Video Background (Xaml/C#)

The task here is to build an application with an infinite loop video background, It might not be very clear what I’m trying to achieve here, so I’ve recorded a video of a simple proof of concept I was working on:

It might look like a straight forward solution by adding a MediaElement with a transparent Grid:

<Page>
<Grid>
<MediaElement />
<Grid Background"Transparent">

</Grid>
</Grid>
</Page>

Which would work just fine; IF the app is just one page app. The issue with this approach, if the user navigates to the next page, the video will start over in the next page.

Before we start working on the correct solution, we need to understand how UWP apps work. Looking at the following image, every UWP app on Windows runs inside one Frame, and the pages will be rendered on that Frame. Every time you want to navigate from a page to another, the Frame will render the new page.

So to have one infinite video which plays on all pages, we just need to add the MediaElement to the Frame level instead of the page level.

To do this, we will need to modify the default template of the Frame. I’ve created the following style to the App.xaml, and gave it the key name “RootFrameStyle”:

<Application.Resources>
<Style x:Key="RootFrameStyle" TargetType="Frame">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Frame">
<Grid>
<MediaElement AutoPlay="True" IsLooping="True" Source="ms-appx:///Assets/Video/Background.mp4" Stretch="UniformToFill" />
<ContentPresenter />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>

All what we did there is changing the template to a Grid. Inside that grid we’ve added a MediaElement control behind the ContentPresenter

After that, in App.xaml.cs we apply the style to the Frame:

rootFrame.Style = Resources["RootFrameStyle"] as Style;

Finally, you will need to set the background color of your page as transparent (so you can see the video through your pages):

<!--<Grid Background="{StaticResource AppBarBackgroundThemeBrush}">-->
<Grid>
<TextBlock Text="Page 1" Foreground="Black" FontSize="50" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>

Done! now you have a beautiful app with a video background.

What else we can do with this apart from having a video background?

  • You can have a video player working on all pages; Hyper app (one of my favorite apps), has a great feature where you can play a video, and navigate to any other page (search page for example) while the video is still playing on the bottom right corner:

You can get the complete source code from this github repository:
https://github.com/TareqAteik/SampleUWPVideoBackground
If you have any question, please reach me out on twitter @tareqateik

Leave a Reply

Your email address will not be published. Required fields are marked *