There is also this much better way of specifying the viewmodel:
using Wpf = System.Windows;
public partial class App : Wpf.Application //your skeleton app already has this.
{
protected override void OnStartup( Wpf.StartupEventArgs e ) //add this.
{
base.OnStartup( e );
MainWindow = new MainView();
MainWindow.DataContext = new MainViewModel( e.Args );
MainWindow.Show();
}
}
The above mechanism applies to the main viewmodel only. To address a comment below which is asking what about user controls, the mechanism translates as follows for child viewmodels:
public class ParentViewModel
{
public MyChildViewModel ChildViewModel { get; }
public ParentViewModel()
{
ChildViewModel = new MyChildViewModel( ... );
}
}
ParentView.xaml:
[...]
xmlns:local="clr-namespace:the-namespace-of-my-wpf-stuff"
[...]
<local:MyChildView DataContext="{Binding ChildViewModel}" />
[...]
<Rant>
All of the solutions previously proposed require viewmodels to have parameterless constructors. Microsoft is under the impression that systems can be built using parameterless constructors. If you are also under that impression, the please, by all means, do go ahead and use some of the other solutions. For those who understand that constructors must have parameters, and therefore the instantiation of objects cannot be left in the hands of magic frameworks, the proper way of specifying the viewmodel is the one I showed above.</Rant>