Setting <Window.DataContext> in XAML

c#, datacontext, mvvm, wpf, xaml

Solution

You'll need an xml namespace mapping to the `ViewModels` namespace. Once you add that, it would be:

<Window.DataContext>
    <vms:MainWindowViewModel />
</Window.DataContext>

(This is assuming you map `vms` to the appropriate namespace.)

This should look just like your current namespace mapping for `local:`, but called `vms:` with the appropriate namespace specified.

Problem

I followed a very simple MVVM example as a basis for my program. The author had one code behind instruction he used in the main page to set the `DataContext`. I'm thinking I should be able to do this in the XAML instead. The MainWindowViewModel is in a directory ViewModels. The code behind works. ``` namespace RDLfromSP { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = new ViewModels.MainWindowViewModel(); } } } ``` I can't seem to find the right combo to set it instead in the XAML ``` <Window x:Class="RDLfromSP.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="300" Width="300" > <Window.DataContext> <local:ViewModels.MainWindowViewModel /> </Window.DataContext> ``` Thanks in advance for your help

Original source