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:

<phone:PhoneApplicationPage
    x:Class="MyApp.MySamplePage"
    x:Name="Self"
    >
    ...
</phone:PhoneApplicationPage>

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Ă  !

Jean-Pierre Thomasset
Development team leaderV3D
Professional web developer and software engineer since 2002. With more than ten years of experience and a solid background in several aspects of IT, I am technically proficient and can handle all kind of software or web projects. I also enjoy learning new things, not limited to computer technologies, which allows me to constantly improve myself.

Specialties:

Expert in .NET development and Web application (C#, ASP.Net, HTML, CSS, Javascript).
Proficient in PHP
Database modeling (SQL Server, MySQL)
Other languages & libraries : Java, C++, AngularJS, jQuery

2 thoughts on “Binding to a class property in XAML

Comments are closed.