Walkthrough: Two-way binding inside a XAML User Control

imageUser controls are a great way couple logic and XAML in an encapsulated way. You can reuse a user control over and over and the logic is isolated from the general flow of your program. This article is not about creating a user control. This article is about binding to a user control.

Not a custom control

A user control contrasts with a custom control in that a custom control contains no XAML. Custom control can be (and is sometimes are required to be) templated (for example, a DataTemplate). Conversely, user controls cannot be templated as the XAML is embedded.

I wrote more about custom controls here: https://blog.jerrynixon.com/2013/01/walkthrough-custom-control-in-xaml-isnt.html

The simplest user control might look like this:

image

Using a user control

The simplest use of a user control would be like this:

image

In the code above, I simply declare the user control and the rest is done for me. What isn’t done in the code is passing information to set the value of any properties or custom properties.

Please note: the data context property of the user control inherits from the parent. A DataTemplate might like this. But user controls don’t anticipate a data context type. Instead, they want properties explicitly set. And we want to bind those properties.

Adding properties

To set a property you need a property. If you are a .Net developer then you will likely start with simple CLR properties. This is a good idea. Like this:

image

Setting such a property is a snap, and it works just fine. You can reference it in the code behind or you can reference it in the XAML. Like this:

image

Trouble binding

But that is a literal value. What about dynamic binding?

Let’s assume your MainPage.xaml.cs loads like this:

image

With that data context set, you might try this:

image

But this fails. It results in “An exception of type 'Windows.UI.Xaml.Markup.XamlParseException' occurred”. And though it says you may safely continue, it doesn’t continue safely at all.

image

What does that mean? It means the binding target isn’t right!

Confused?

Read the whole article here.