0
votes

I have a WPF application which uses a WPF user control.

The user control exposes a DependencyProperty to which I would like to bind to in my WPF application.

As long as my user control does not set its own DataContext this works and I am able to listen to changes in the DependencyProperty.

However the moment I set the DataContext the PropertyChanged being called is null.

What am I missing here?

Code sample: https://skydrive.live.com/redir.aspx?cid=367c25322257cfda&page=play&resid=367C25322257CFDA!184

3
You will get more help if you post a simple code sample demonstrating the problem here, instead of posting links to an external site... - Abe Heidebrecht

3 Answers

0
votes

DependencyProperty has inheritance property, so if you don't set the UserControlDP's DataContext, the DataContext is inherited from the MainWindow's DataContext. In this case, the UserControlDP's DataContext in your code below is set as MainWindow_ViewModel. Thus, the binding is correctly executed.

<usercontrol:UserControlDP Width="200" Height="100"
    TestValue="{Binding TestValueApp, Mode=TwoWay, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}"
    Margin="152,54,151,157"></usercontrol:UserControlDP>

In the other case, UserControlDP's DataContext is set as UserControlDP_ViewModel, so the binding is broken. You can see the first exception message as the following at the debug window.

System.Windows.Data Error: 40 : BindingExpression path error: 'TestValueApp' property not found on 'object' ''UserControlDP_ViewModel' (HashCode=24672987)'. BindingExpression:Path=TestValueApp; DataItem='UserControlDP_ViewModel' (HashCode=24672987); target element is 'UserControlDP' (Name=''); target property is 'TestValue' (type 'Object')
0
votes

Consider setting the DataContext on one of the elements contained within UserControl rather than on UserControl itself.

0
votes

Thanks for the input and clarifying the details.

After giving it some thought I took the easy way out and removed the ViewModel from the control. MVVM for the application but no MVVM for the user control.

This way I do not use any bindings in the user control, instead use Dependency Properties which are bound to in the Main application.