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:

  1. Thanks Anders. You just made my day!

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

    ReplyDelete
  3. Thanks!!! This is exactly what I was looking for!

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

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

    ReplyDelete
  6. THANK YOU !!!!!!!!!!!!!!!!!

    You save my day !! :D

    ReplyDelete
  7. 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.

    ReplyDelete