How to instantiate DataContext object in XAML

Gus Paul picture Gus Paul · Oct 5, 2009 · Viewed 42.8k times · Source

I want to be able to create an instance of the DataContext object for my WPF StartupUri window in XAML, as opposed to creating it code and then setting the DataContext property programmaticly.

The main reason is I don't need to access the object created externally and I don't want to have to write code behind just for setting the DataContext.

I'm sure I've read somewhere how to instantiate the DataContext object in XAML but I can't find it in any of the usual places...

Answer

Steven Robbins picture Steven Robbins · Oct 5, 2009

You add an XML namespace for whatever namespace your DataContext lives in, create an instance of it in the Window Resources and set the DataContext to that resource:

<Window x:Class="WpfApplication4.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication4"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <local:MyViewModel x:Key="MyViewModel"/>
    </Window.Resources>
    <Grid DataContext="{StaticResource MyViewModel}">

    </Grid>
</Window>