Binding to a class property in XAML

Binding something in your XAML file to a property in your underlying partial class is pretty easy once you know the trick. You only have to name your XAML base object. For example, here is a PhoneApplicationPage declaration:


I always give “Self” as my object name as I find using “Self” in the binding declaration makes the binding obvious but you can use the name you want. My example is for a Windows Phone application however the same mechanism works for any XAML desktop application.

Then you define a property in your class, for example

namespace MyApp
    public partial class MySamplePage : PhoneApplicationPage
        public String MyStringProperty { get { return "Binded string"; } }

Now, you can use some binding magic in your XAML file to map a node property to a class property :

<TextBlock Text="{Binding MyStringProperty, ElementName=Self}" />

And VoilĂ  !