DataContextAwareViewModelInitializer'CreateViewModel

Jul 28, 2010 at 4:01 PM
Edited Jul 28, 2010 at 4:01 PM

in DataContextAwareViewModelInitializer.cs:

 public override void CreateViewModel(Export viewModelContext,
            FrameworkElement containerElement)
        {

...........


            if(Designer.IsInDesignMode)
            {
                base.CreateViewModel(viewModelContext, containerElement ); // this will create the VM and set it as DataContext

                //if the ViewModel is an IDataContextAware ViewModel then we should call the DesignTimeInitialization
                var dataContextAwareVM = containerElement.DataContext as IDesignTimeAware;
                if (dataContextAwareVM != null)
                    dataContextAwareVM.DesignTimeInitialization();
            }
        }

 

above three red line has been  called in base.CreateViewModel(viewModelContext, containerElement );

Why call it again?

Thanks!

Coordinator
Jul 29, 2010 at 8:01 AM

DataContextAware ViewModels do not get created by MEFedMVVM at runtime... ONLY AT DESIGN TIME.

 

The idea with DataContextAware ViewMOdels are ViewModels that are injected by the user code (example if you have a scenario of an implicit DataTemplate).

 

http://marlongrech.wordpress.com/2010/05/23/mefedmvvm-v1-0-explained/

Jul 29, 2010 at 11:42 AM

DataContextAwareViewModelInitializer's base class is BasicViewModelInializer

so base.CreateViewModel(viewModelContext, containerElement );  will call BasicViewModelInializer's CreateViewModel  as below:

public virtual void CreateViewModel(Export viewModelContext, FrameworkElement containerElement)
        {
........

            if (Designer.IsInDesignMode)
            {
                //if the ViewModel is an IDataContextAware ViewModel then we should call the DesignTimeInitialization
                var dataContextAwareVM = containerElement.DataContext as IDesignTimeAware;
                if (dataContextAwareVM != null)
                    dataContextAwareVM.DesignTimeInitialization();
            }
        }

You can see, if at design time,  the above three line code will called two times, one time in DataContextAwareViewModelInitializer's CreateViewModel method, and the other time  is in BasicViewModelInializer's CreateViewModel method.

Thanks!

Coordinator
Jul 29, 2010 at 11:59 AM

ow ok.... yea DesignTimeInialization method would be called 2 times... I will fix this (removing the 3 lines you marked in red).

Thanks for pointing it out