views:

95

answers:

3

I wrote a custom Silverlight 3 control that uses a class as its data context (MVVM pattern). I want to place this control on another control (form) through XAML. The child control exposes a Dependency Property that when set through XAML, will make it show detailed info.

So an example is that the child control shows order details data, and I want to place it on a form that show user orders. When you select an order, the selected item value on the parent control (orders list), is data bound to the child control, to show details.

The problem is that the child control’s dependency property's OnChanged handler never gets called. If I do not set a data context on the child (so it uses the parent's data context) all works fine, but when I set a different data context, it breaks down.

A: 

Ideally, your ViewModel would be for the outer UserControl and a property on the ViewModel will be the DataContext of the Inner/Child userControl

But why would you want to do that. That would make the two controls dependent on each other. This means that I put my UI logic into the VM. I would like the designer to be able to "mix and match" contorls.
Noam
A: 

Its true that when the Parent control's DataContext is set, it is propogated down to all its child controls. But the child control has an option of overriding this behavior by setting its own DataContext (which you seem to be doing in your example). Hence by the rule of preferences, the child control's DataContext is given more preference and thus it overrides the parent's one. Also since the child's DataContext never changes after it's initially set, the DP never gets invoked.

Sudeep
Not sure I understand your point. It does not explain why the DP does not get called. What does the Data Context have to do with a DP?
Noam
A: 

So I thought about this some more, and I understand what is happening, but I think its very confusing, and is not done right. If I am doing data binding on a control in the main page, it should use the context of that page to do the binding. And binding I do inside the control should use the control's context.

The way it works now uses the control's context no matter where I put the binding expression (unless I am doing E2E binding, then its using the main page's context). That is silly to me. But at least I understand it now.

I solved the problem using Element to Element binding, and got it to work. I hope the SL team would change this behavior.

Noam