I also struggled with the concept of putting a DataContext into my views (UserControls).
Does the idea of โโexposing view models for children using the main window view model have a limited appeal?
The following idea works, but you get negative feedback from the Visual Studio IDE.
My App.xaml.cs looks like this:
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); UnityContainer unityContainer = new UnityContainer(); this.Properties["UnityContainer"] = unityContainer; unityContainer.LoadConfiguration(); unityContainer.Resolve<MainWindow>().Show(); } public static IUnityContainer UnityContainer { get { return (IUnityContainer)App.Current.Properties["UnityContainer"]; } }
I registered my containers in App.config, but this is just a personal choice.
In my user control code, I have the following:
protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); this.DataContext = App.UnityContainer.Resolve<MyViewModel>(); }
In the above example, MyViewModel is not registered and does not have an interface.
As I said above, it works for me, but the IDE complains about the impossibility of creating an instance of a user control. However, if you run the application, it works great.
Allan source share