A blog about one man's journey through code… and some pictures of the Peak District

Always in the last place you look (programmatically finding controls in a C# / XAML store app)

I’ve seen a few articles on this, but none dealing directly with a Windows 8 Store App. Not that much changes in the general approach, but this article is more about working out why the wheel is round than trying to re-invent it.

The Problem

So, the basis for the article is a standard sample Windows 8 Grid App in C# / XAML. Here’s the XAML as it stands – it should fit neatly into the template Grid app with a bit of adaptation:

So to quickly summarise, I have a media element and a play button. So, the actual media file will, in real life, be bound to the data source, but the play button should have the same effect regardless. The problem that I have it that I can’t reference the MediaElement “media”, because the code behind doesn’t know which “media” I mean.

The Solution

To start off with, let’s have a look at the visual tree (this should also guide the way to the solution). This function tells me what the XAML visual tree looks like:

Okay – so now we know what the visual tree looks like, so let’s see if we can work out what each element is called. The trick to this is just casting the FrameworkElement (change the DisplayVisualTree function as follows):

This does look like a lot of trouble to go to to simply control a media element (especially since sinple clicking the element itself will start the play), however, once you start dealing with databound XAML, it’s only a matter of time before you decide you need to access and control an element inside a databound template.