Wednesday, December 19, 2007

Bind from XAML to a local property in code-behind

When I learned WPF I couldn´t figure out how to create a simple binding from my XAML to some property in my code-behind file. Now when I know I thought that I should share this small piece of knowledge and spare you the frustration that I had.

One way to create a binding is to bind to another element in your XAML-file. E.g. Text=”{Binding SomeProperty, ElementName=MyOtherElement}” where SomeProperty is a property in your MyOtherElement. MyOtherElement is the name (x:Name) of an element in your XAML-file. With this knowledge we just set a name on our root element (Window, Page, UserControl or whatever) x:Name="myRoot" and then refer to that name in ElementName. E.g Text="{Binding MyLocalProperty, ElementName=myRoot }". The MyLocalProperty is then a property in our code-behind file. This can be a standard property or a dependency property.

Download the sample project (BindToAPropertyDemo.zip).

9 comments:

rathbone1200cc said...

Thanks! quick and helpful.

Carl Remmers said...

Thanks Anders. You just made my day!

Duke said...

Thank you! this is EXACTLY what i'm searching for! very useful

Krish said...

Thanks!!! This is exactly what I was looking for!

Anonymous said...

Thanks. i have been googling for a couple of hours..

wouterx said...

The link to http://www.bursjoo.se/userfiles/Media/BindToAPropertyDemo.zip is not working anymore..

Nicolas said...

THANK YOU !!!!!!!!!!!!!!!!!

You save my day !! :D

Nathan said...

Where is the demo for this? I am trying my hardest to get this to work and it always fails. Your download link does not work anymore.

JK said...

Thank you much!