Inject ViewModel of base view into contained UserControl

Topics: Questions
Jul 16, 2012 at 7:37 AM


how can I inject the current datacontext as ViewModel instance into a UserControl on the same window?
My goal is that the usercontrol uses the same viewmodel instance as the window.

I've tried to override UserControl.GetViewModelInstance(), but this method is not called.

        protected override IViewModel GetViewModelInstance(object dataContext)
            return (dataContext is IViewModel)
                ? (IViewModel)dataContext
                : base.GetViewModelInstance(dataContext);

Thanks, alex.

Jul 17, 2012 at 12:06 AM
Edited Jul 17, 2012 at 12:06 AM


maybe this is what you are searching for:


     <!-- DataContext is bound to window viewmodel -->

     <!-- "inject" window viewmodel as viewmodel into the custom user control... if catel finds on usercontrol initialization a viewmodel in the controls' datacontext the procedure for finding/creating a new one is skipped -->
     <CustomUserControl DataContext="{Binding}" />


You can also find a description about it in the catel documentation (section faq/mvvm)....

Hope this helps you...

Jul 17, 2012 at 3:16 PM

Thanks, that helped.

I actually got it working after adding this to the controls code:

        protected override System.Type GetViewModelType()
            return typeof(ViewModels.TheInjectedViewModel);

Jul 18, 2012 at 7:40 AM

Great that you found out how to do this. Good job.