Jerry Nixon - MSFT Jerry Nixon - MSFT - 2 months ago 5
C# Question

How do you bind to the property of a User Control?

In Windows Store Apps, you create a user control to encapsulate and reuse code-behind and layout XAML. A simple user control might look like this:

<TextBlock Text="First Name" />
<TextBox x:Name="MyTextBox" />

Now, I want to setup binding. So I create code-behind with properties that expose the Text properties of the UI controls. Something like this:

public string TextBoxText
get { return MyTextBoxText.Text; }
set { MyTextBoxText.Text = value; }

However, this does not work. It seems like data binding to a user control is a valuable part of a XAML UI. But how is it accomplished?


There is only one implementation of a property in a user control that supports binding in the consuming page. That is a dependency property. The implementation is simple enough, but you must also include the changed event to interact directly with the UI, since a dependency property is a static property on a control. Like this:

public string TextBoxText
    get { return (string)GetValue(TextBoxTextProperty); }
    set { SetValue(TextBoxTextProperty, value); }

public static readonly DependencyProperty TextBoxTextProperty =
    DependencyProperty.Register("TextBoxText", typeof(string), typeof(MyUserControl),
    new PropertyMetadata(string.Empty, OnTextBoxTextPropertyChanged));

private static void OnTextBoxTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    (d as MyUserControl).MyTextBox.Text = e.NewValue.ToString();

I admit, this is not super obvious. But hopefully now that you know, it will save you hours of searching and trying to figure out. Again, you can only bind to a dependency property of a user control. And, you can only set the UI values off the static thread using the changed event.

Best of luck!