3

What is the "best" (or the most-often-used) approach when binding a complex class to a user control for re-use?

I am trying to create some reusable libraries for classes, and I am not sure which approach I should use. Example: I want to create an Address library that defines and Address class (with properties Line1, Line2 etc.), it's validation logic and an AddressControl which acts as the viewer/editor with bound fields for each property.

In use I might have a customer class with BillingAddress, DeliveryAddress properties and I would want to bind these in my customer control thus:

<addressLib:AddressControl [xxx]="{Binding BillingAddress}" />

So the question is what do I put in XXX?

Initially I thought of creating a DependencyProperty 'Address' on the control:

<addressLib:AddressControl Address="{Binding BillingAddress}" />

But now I am thinking surely I could just use the existing DataContext property?

<addressLib:AddressControl DataContext="{Binding BillingAddress}" />

Is this the best approach? Are there any issues e.g. updates or NotifyPropertyChange issues?

many thanks for your help!

Quango
  • 12,338
  • 6
  • 48
  • 83

2 Answers2

1

Setting the DataContext of your control to your model (in this case a BillingAddress) is the way to go. If your Control is used in a DataTemplate for an ItemsControl then the DataContext would be of course just "{Binding}".

Oliver Weichhold
  • 10,259
  • 5
  • 45
  • 87
1

One difference to remember is that with dependency property you get change notification and with datacontext you don't (at least not untill SL5 is out)

Denis
  • 4,115
  • 1
  • 18
  • 20
  • Thanks for warning - I think I could possibly raise an event from the control to indicate the change. – Quango May 25 '11 at 15:13
  • I've change this to be the correct answer, as using the DataContext is not reliable as you don't get the change notification. While it's not wrong it makes the control a One-Time binding and it won't update if the parent control changes the datacontext. That's a fairly limited use case IMHO, so the dependency property approach is the right one. – Quango Aug 12 '11 at 08:43
  • If anyone is interested this answer: http://stackoverflow.com/questions/421581/silverlight-binding-a-child-controls-property-to-a-property-in-a-user-control/2528018#2528018 demonstrates the best approach to binding values in controls. – Quango Aug 12 '11 at 10:09