The question pretty much says it all.
I have a window, and have tried to set the DataContext using the full namespace to the ViewModel, but I seem to be doing something wrong.
<Window x:Class="BuildAssistantUI.BuildAssistantWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="BuildAssistantUI.ViewModels.MainViewModel">
Try this instead.
<Window x:Class="BuildAssistantUI.BuildAssistantWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:VM="clr-namespace:BuildAssistantUI.ViewModels">
<Window.DataContext>
<VM:MainViewModel />
</Window.DataContext>
</Window>
You need to instantiate the MainViewModel and set it as datacontext. In your statement it just consider it as string value.
<Window x:Class="BuildAssistantUI.BuildAssistantWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BuildAssistantUI.ViewModels">
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
There is also this 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 ) //you need to add this.
{
base.OnStartup( e );
MainWindow = new MainView();
MainWindow.DataContext = new MainViewModel( e.Args );
MainWindow.Show();
}
}
<Rant>
All of the solutions previously proposed require that MainViewModel
must have a parameterless constructor.
Microsoft is under the impression that systems can be built using parameterless constructors. If you are also under that impression, go ahead and use some of the other solutions.
For those that know 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>
You might want to try Catel. It allows you to define a DataWindow class (instead of Window), and that class automatically creates the view model for you. This way, you can use the declaration of the ViewModel as you did in your original post, and the view model will still be created and set as DataContext.
See this article for an example.
Source: Stackoverflow.com