Link to home
Start Free TrialLog in
Avatar of chuang4630
chuang4630

asked on

How to add DataContext to User Control's XAML?

How to add DataContext to User Control's XAML?

I have a user control MyControl, it needs to be bound to its view model: MyControlViewModel. I have no problem to add the DataContext programmically in the constructor. But I was told this  is not allowed. It has to be done in the XAML. However, I have gotten the error in XAML

MyControlViewModel is in the project MyProject.ViewModel

<UserControl  .....
   xmlns:local="clr-namespace:MyProject.ViewModel"    
   ......
   >
    <UserControl.DataContext>
        <local:MyControlViewModel/>        // ERROR: The name MyControlViewModel does not exist in the namespace "clr-namespace:MyProject.ViewModel"  

    </UserControl.DataContext>

   <UserControl.Resources>
     
      // Style stuff...

   </UserControl.Resources>
</UserControl>


Anyone can help me?

Thanks a lot.
Avatar of Aaron Jabamani
Aaron Jabamani
Flag of United Kingdom of Great Britain and Northern Ireland image

Can you please add the assembly name and check. Open the assembly in object explorer  and check whether the class you are looking for is available.

<UserControl  .....
   xmlns:local="clr-namespace:MyProject.ViewModel, <assembly name>"
ASKER CERTIFIED SOLUTION
Avatar of chuang4630
chuang4630

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of chuang4630
chuang4630

ASKER

I have a right solution