Setting up SwapChainBackgroundPanel in a XAML app

Monday, July 30, 2012


After creating a XAML app for Windows 8 using the Blank XAML app template, I changed the body of MainPage.xaml from this:

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
</Grid>
to this:
<SwapChainBackgroundPanel></SwapChainBackgroundPanel>

While this compiles without warnings, it crashes on launch. With a C++/XAML app, a console message appears:

First-chance exception at 0x754F7945 (KernelBase.dll) in HelloWorld.exe: 0x40080201: WinRT originate error (parameters: 0x80004005, 0x0000005E, 0x031FDCE4).

In both C++ and C#, the exception message is as follows:

Page element must be root of visual tree when its content is SwapChainBackgroundPanel element.

This is because the default XAML template creates a Frame that hosts your app's pages, and it, not the Page object, is the root. To remove it, edit App.xaml.cpp's OnLaunched() function and replace this:

// Create a Frame to act navigation context and navigate to the first page
auto rootFrame = ref new Frame();
if (!rootFrame->Navigate(TypeName(MainPage::typeid)))
{
    throw ref new FailureException("Failed to create initial page");
}

// Place the frame in the current Window and ensure that it is active
Window::Current->Content = rootFrame;
Window::Current->Activate();

with this:

Window::Current->Content = ref new MainPage();
Window::Current->Activate();

If you're using C# and not C++, it's pretty much identical. Just omit the ref before new MainPage().

If you want to learn more about Direct3D and XAML, there is a good article on MSDN about the interop options available.

Tags: directx, direct3d, xaml, winrt, metro | Posted at 15:48 | Comments (6)


Comments

Chad on Tuesday, October 2, 2012 at 10:13

Thanks for this information. It was very useful to me!

J on Friday, November 9, 2012 at 04:44

Thank you very, very much!

Phil on Saturday, December 15, 2012 at 15:45

Was running into the same issue and this resolved it. Thanks!

Eric on Monday, October 14, 2013 at 10:58

thank you! been looking at this bug for two days :/

ecosky on Friday, November 15, 2013 at 10:23

Thanks, this was a very helpful post!

miaodada on Sunday, July 5, 2015 at 00:01

Thank you. This help me so much.

Add a comment

Name:
Email: (optional, not displayed to public)
URL: (do not fill this in — leave blank!)

Comment: