Geeks With Blogs

News



Add to Google

Tim Hibbard CEO for EnGraph software

Intro to this series of posts.

There are a ton of posts out there about data binding with INotifyPropertyChanged objects in WPF, so I won't regurgitate what other people have already written.  There is one point that I haven't see much clear documentation about that I would like to cover.

Hosting data bound custom controls.

Let's say we have a location control that is bound to a location object like so:

<TextBox Text="{Binding Path=Address1}"/> <TextBox Text="{Binding Path=Address2}"/>

And you host this location control in your client control like so:

<runtime:LocationControl x:Name="ClientLocation" MinWidth="200" />

I've seen a bunch of examples where DependencyProperties have to be implemented on the LocationControl in order to bind the control to your data.  An easier way seems to be to listen to the DataContextChanged event of the top level element that has it's DataContext set.  In my code, I set the DataContext of the actual control, so my code looks like this:

public Client() { InitializeComponent(); this.DataContextChanged += new DependencyPropertyChangedEventHandler(Client_DataContextChanged); } void Client_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { this.ClientLocation.DataContext = ((Entities.Client)this.DataContext).Location; }

Now when the data bindings change on the Client control, my Location control will also reflect the new data.

 

Posted on Monday, July 16, 2007 12:03 PM .NET , Goldstar , WPF | Back to top


Comments on this post: Real world desktop WPF applications - Data binding

# re: Real world desktop WPF applications - Data binding
Requesting Gravatar...
make sure you are aware that the DataContextChanged event fires independent of the completion of bindings relative to the DataContext - in other words the event can fire either before, after, or during the DependencyProperties reliant on the DataContext having their values updated.

you can find a warning on this here:
http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.datacontextchanged.aspx
"The data binding engine is not deterministic about the order of these reevaluations, relative to the raising of the DataContextChanged event. The reevaluations can occur before the event, after the event, or in any mixture."

I just ran into this issue today, and wish I had known about it before..
Left by Smartyp on Sep 22, 2008 7:22 PM

Your comment:
 (will show your gravatar)


Copyright © Tim Hibbard | Powered by: GeeksWithBlogs.net