How to instantiate DataContext object in XAML How to instantiate DataContext object in XAML wpf wpf

How to instantiate DataContext object in XAML


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>


You can just specify this directly in XAML for the entire Window:

<Window     ... xmlns definitions ...>   <Window.DataContext>        <local:CustomViewModel />   </Window.DataContext></Window>

This creates a view model named "CustomViewModel" in the namespace aliased to local, directly as the DataContext for the Window.


Assuming this code:

public abstract class BaseView { }public class RuntimeView : BaseView { }public class DesigntimeView : BaseView { }

Try this:

<Page.DataContext>    <local:RuntimeView /></Page.DataContext><d:Page.DataContext>    <local:DesigntimeView /></d:Page.DataContext><ListBox ItemsSource="{Binding}" />

Best of luck!