To achieve complete decoupling, set ViewModels on the ResourceDictionary
found on the main App class. There are two ways to do this, and for the most part it doesn't matter which method is used. There are trade-offs however.
Method 1
If it is done progamatically, you must ensure Dictionary keys match. This causes a weak coupling between the strings defined in the XAML and those defined programmatically. Not ideal, but not the end of the world either. The advantage here is that ability to use constructor injection.
//App.xaml.cs
//This line invoked somewhere after App OnStartUp function is called.
MainViewModel mainViewModel = new MainViewModel( new Dependency() );
Current.ResourceDictionary["MainViewModel"] = mainViewModel;
//MainView.xaml
<Window DataContext="{StaticResource MainViewModel}">
The Business logic doesn't care what a View is, and the application can be Bootstrapped in any way... using factory/builder object or any IOC container. (As long as it all starts in the OnStartUp function).
Method 2
Define ViewModels in App.xaml
using Application.Resource
. Using this method all key names will be located in XAML, which feels pretty nice. The only negative result is that .NET automatically builds the ViewModels, forcing the to provide default constructors. Sometimes it is desirable for the IOC container to build your objects, or use Constructor Injection in custom factories/builders.
//App.xaml
<Application
xmlns:local="clr-namespace:ViewModels" />
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary>
<local:MainViewModel x:key="MainViewModel" />
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
//App.xaml.cs
MainViewModel mainViewModel = Current.ResourceDictionary["MainViewModel"];
mainViewModel.propertyInjection = new Dependency();
//MainView.xaml
<Window DataContext="{StaticResource MainViewModel}">
Both ways are valid options, and with a little key management, a mix and match can be used to suit requirements.