Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set datacontext of child UserControl in WPF

I am not able to set the datacontext of the UserControl (the UserControl is nested within other UserControl).

I have the below structure:

Views/ViewModels:

MainControl <-> MainViewModel <br>
UserControlA <-> ViewModelA<br>
UserControlB <-> ViewModelB<br><br>
ViewModels:<br>

ViewModelB is a property of ViewModelA MainViewModel instantiates ViewModelA and ViewModelB in the ctor.

Views:
MainControl contains UserControlA, which in turn contains UserControlB MainControl assigns the ViewModelA as the datacontext ( This works as expected )

<!-- MainControl Xaml-->
<UserControl x:Name="MainControl">

<views:UserControlA DataContext="{Binding ViewModelA}" />

</UserControl>

In UserControlA i doing the same thing as in the MainControl , binding the datacontext of UserControlB to its ViewModel which is a property in the ViewModelA This is not working as expected...

   <!-- USerControlA Xaml-->
    <UserControl>
    .....
    .....

    <views:UserControlB DataContext="{Binding DataContext.ViewModelB}" /> 

   </UserControl>
like image 570
Masood Alam Avatar asked Jun 29 '14 02:06

Masood Alam


1 Answers

Change the datacontext binding for UserControlB to:

<UserControl>
    <views:UserControlB DataContext="{Binding ViewModelB}" /> 
</UserControl>
like image 66
Stuart Avatar answered Oct 19 '22 00:10

Stuart