How to access parent's DataContext from a UserControl - wpf

I need to access the container's DataContext from a UserControl (a grid containing textboxes and a listbox: I need to insert items in this list box) that I created in WPF: which is the best way to do it?
I was thinking to pass the DataContext as parameter to user control but think there is a cleaner way to do it.

Normally the DataContext will be inherited, just do not explicitly set it on the UserControl and it will get it from its parent. If you have to set it you could still use the Parent property to get the parent, which you then can safe-cast to a FrameworkElement and if it is not null you can grab its DataContext.

I sometimes have nested User controls and a grandchild usercontrol sometimes needs the grandparent's view's data context. The easiest way I have found so far (and I'm somewhat of a newbie) is to use the following:
<Shared:GranchildControl DataContext="{Binding RelativeSource={RelativeSource
FindAncestor, AncestorType={x:Type GrandparentView}},
Path=DataContext.GrandparentViewModel}" />
I wrote up a more detailed example on my blog if you want more specifics.

Add this BindingProxy class to your project:
using System.Windows;
namespace YourNameSpace
{
/// <summary>
/// Add Proxy <ut:BindingProxy x:Key="Proxy" Data="{Binding}" /> to Resources
/// Bind like <Element Property="{Binding Data.MyValue, Source={StaticResource Proxy}}" />
/// </summary>
public class BindingProxy : Freezable
{
protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
}
public object Data
{
get { return (object)GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}
public static readonly DependencyProperty DataProperty = DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy));
}
}
Add the BindingProxy to your UserControl's resources.
Set the 'Data' property of the BindingProxy to whatever you need, e.g. search for a parent Window. Data="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}},Path=DataContext}" If you needed something more complex you could use a custom converter.
Now you have access to that parent's DataContext: {Binding Data.MyCommand, Source={StaticResource BindingProxy}}
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:common="clr-namespace:YourNameSpace;assembly=YourAssembly"
mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<common:BindingProxy x:Key="BindingProxy" Data="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}},Path=DataContext}" />
</UserControl.Resources>
<Border>
<Button Command="{Binding Data.MyCommand, Source={StaticResource BindingProxy}}">Execute My Command</Button>
<!-- some visual stuff -->
</Border>
</UserControl>

H.B. answers the question in your title.
However the text poses a different design question. I'd ask you to reconsider your design.
A control inherits the DataContext property of its ancestor as long as no one in between explicitly overrides.
If the user control needs data, it should get it from its data source (a viewmodel for the user control). So in this case, the user control can obtain the data it needs from the ListItemsForDisplay property exposed on the SomeViewModel instance. No need to get parent and cast.. much cleaner.
<ContainerType DataSource={Binding SomeViewModel}>
<YourUserControl>
<ListBox ItemsSource={Binding ListItemsForDisplay}"/>
...

In this case, UserControl will get DataContext windows
<Window>
<local:MyUserControl DataContext="{Binding}"/>
</Window>

Related

Binding fails when used inside MenuItem.Icon

I want to offer a context menu with an item that has a color swatch in the space where "icons" are normally placed for such menu items, i.e. the space corresponding to MenuItem.Icon.
But the color swatch is dynamic--a Brush property on the UserControl that (in this crafted example) changes to a random color in response to the ContextMenuOpening event--and my attempt at binding to it is failing.
When run, the menu item has no content in the Icon space, and Visual Studio's output contains an error that doesn't seem like it ought to be happening.
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ContextMenu', AncestorLevel='1''. BindingExpression:Path=PlacementTarget.RandomBrush; DataItem=null; target element is 'Rectangle' (Name=''); target property is 'Fill' (type 'Brush')
Here's the XAML for the control:
<UserControl x:Class="ContextMenuItemIconTest.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.ContextMenu>
<ContextMenu>
<MenuItem Header="Do something">
<MenuItem.Icon>
<Rectangle Width="16" Height="16" Fill="{Binding PlacementTarget.RandomBrush, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" />
</MenuItem.Icon>
</MenuItem>
</ContextMenu>
</UserControl.ContextMenu>
<Grid>
</Grid>
And the code behind:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace ContextMenuItemIconTest
{
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
ContextMenuOpening += UserControl1_ContextMenuOpening;
}
void UserControl1_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
Random r = new Random();
RandomBrush = new SolidColorBrush(Color.FromRgb((byte)r.Next(256), (byte)r.Next(256), (byte)r.Next(256)));
}
#region RandomBrush (Dependency Property)
public Brush RandomBrush
{
get { return (Brush)GetValue(RandomBrushProperty); }
set { SetValue(RandomBrushProperty, value); }
}
public static readonly DependencyProperty RandomBrushProperty =
DependencyProperty.Register(
"RandomBrush",
typeof(Brush),
typeof(UserControl1),
new PropertyMetadata(new SolidColorBrush(Colors.Blue)));
#endregion
}
}
Not sure if there is a better solution but I think the scenario here is very tricky. The Icon content seems to be detached completely from the visual tree. So you cannot use Binding with RelativeSource or ElementName and strangely even setting the Source to some {x:Reference} causes some cyclic reference error.
I just could think of this work-around, a little hacky but it's acceptable. There is an interesting knowledge about the Freezable object. Binding inside it (set for some property) can use RelativeSource as well as ElementName even when it's just declared as a resource (added to Resources). So in this case we can try using some object deriving from Freezable to act as the proxy. Because this proxy is declared as a resource, we can set the Binding inside Icon with Source being set to some StaticResource referencing the proxy. Then it would work. There are many objects deriving from Freezable for your choice, you can even create your own class. But I would like to use something existing here. The DiscreteObjectKeyFrame is the most suitable object to use. Technically its Value property can hold any kind of object. Now's the working code:
<ContextMenu>
<ContextMenu.Resources>
<!-- the proxy here -->
<DiscreteObjectKeyFrame x:Key="o" KeyTime="0"
Value="{Binding PlacementTarget.RandomBrush,
RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
</ContextMenu.Resources>
<MenuItem Header="Do something">
<MenuItem.Icon>
<Rectangle Width="16" Height="16"
Fill="{Binding Value, Source={StaticResource o}}" />
</MenuItem.Icon>
</MenuItem>
</ContextMenu>

How to correctly bind to a dependency property of a usercontrol in a MVVM framework

I have been unable to find a clean, simple, example of how to correctly implement a usercontrol with WPF that has a DependencyProperty within the MVVM framework. My code below fails whenever I assign the usercontrol a DataContext.
I am trying to:
Set the DependencyProperty from the calling ItemsControl , and
Make the value of that DependencyProperty available to the ViewModel of the called usercontrol.
I still have a lot to learn and sincerely appreciate any help.
This is the ItemsControl in the topmost usercontrol that is making the call to the InkStringView usercontrol with the DependencyProperty TextInControl (example from another question).
<ItemsControl ItemsSource="{Binding Strings}" x:Name="self" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel HorizontalAlignment="Left" VerticalAlignment="Top" Orientation="Vertical" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<DataTemplate.Resources>
<Style TargetType="v:InkStringView">
<Setter Property="FontSize" Value="25"/>
<Setter Property="HorizontalAlignment" Value="Left"/>
</Style>
</DataTemplate.Resources>
<v:InkStringView TextInControl="{Binding text, ElementName=self}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Here is the InkStringView usercontrol with the DependencyProperty.
XAML:
<UserControl x:Class="Nova5.UI.Views.Ink.InkStringView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
x:Name="mainInkStringView"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="{Binding TextInControl, ElementName=mainInkStringView}" />
<TextBlock Grid.Row="1" Text="I am row 1" />
</Grid>
</UserControl>
Code-Behind file:
namespace Nova5.UI.Views.Ink
{
public partial class InkStringView : UserControl
{
public InkStringView()
{
InitializeComponent();
this.DataContext = new InkStringViewModel(); <--THIS PREVENTS CORRECT BINDING, WHAT
} --ELSE TO DO?????
public String TextInControl
{
get { return (String)GetValue(TextInControlProperty); }
set { SetValue(TextInControlProperty, value); }
}
public static readonly DependencyProperty TextInControlProperty =
DependencyProperty.Register("TextInControl", typeof(String), typeof(InkStringView));
}
}
That is one of the many reasons you should never set the DataContext directly from the UserControl itself.
When you do so, you can no longer use any other DataContext with it because the UserControl's DataContext is hardcoded to an instance that only the UserControl has access to, which kind of defeats one of WPF's biggest advantages of having separate UI and data layers.
There are two main ways of using UserControls in WPF
A standalone UserControl that can be used anywhere without a specific DataContext being required.
This type of UserControl normally exposes DependencyProperties for any values it needs, and would be used like this:
<v:InkStringView TextInControl="{Binding SomeValue}" />
Typical examples I can think of would be anything generic such as a Calendar control or Popup control.
A UserControl that is meant to be used with a specific Model or ViewModel only.
These UserControls are far more common for me, and is probably what you are looking for in your case. An example of how I would use such a UserControl would be this:
<v:InkStringView DataContext="{Binding MyInkStringViewModelProperty}" />
Or more frequently, it would be used with an implicit DataTemplate. An implicit DataTemplate is a DataTemplate with a DataType and no Key, and WPF will automatically use this template anytime it wants to render an object of the specified type.
<Window.Resources>
<DataTemplate DataType="{x:Type m:InkStringViewModel}">
<v:InkStringView />
</DataTemplate>
<Window.Resources>
<!-- Binding to a single ViewModel -->
<ContentPresenter Content="{Binding MyInkStringViewModelProperty}" />
<!-- Binding to a collection of ViewModels -->
<ItemsControl ItemsSource="{Binding MyCollectionOfInkStringViewModels}" />
No ContentPresenter.ItemTemplate or ItemsControl.ItemTemplate is needed when using this method.
Don't mix these two methods up, it doesn't go well :)
But anyways, to explain your specific problem in a bit more detail
When you create your UserControl like this
<v:InkStringView TextInControl="{Binding text}" />
you are basically saying
var vw = new InkStringView()
vw.TextInControl = vw.DataContext.text;
vw.DataContext is not specified anywhere in the XAML, so it gets inherited from the parent item, which results in
vw.DataContext = Strings[x];
so your binding that sets TextInControl = vw.DataContext.text is valid and resolves just fine at runtime.
However when you run this in your UserControl constructor
this.DataContext = new InkStringViewModel();
the DataContext is set to a value, so no longer gets automatically inherited from the parent.
So now the code that gets run looks like this:
var vw = new InkStringView()
vw.DataContext = new InkStringViewModel();
vw.TextInControl = vw.DataContext.text;
and naturally, InkStringViewModel does not have a property called text, so the binding fails at runtime.
You're almost there. The problem is that you're creating a ViewModel for your UserControl. This is a smell.
UserControls should look and behave just like any other control, as viewed from the outside. You correctly have exposed properties on the control, and are binding inner controls to these properties. That's all correct.
Where you fail is trying to create a ViewModel for everything. So ditch that stupid InkStringViewModel and let whoever is using the control to bind their view model to it.
If you are tempted to ask "what about the logic in the view model? If I get rid of it I'll have to put code in the codebehind!" I answer, "is it business logic? That shouldn't be embedded in your UserControl anyhow. And MVVM != no codebehind. Use codebehind for your UI logic. It's where it belongs."
Seems like you are mixing the model of the parent view with the model of the UC.
Here is a sample that matches your code:
The MainViewModel:
using System.Collections.Generic;
namespace UCItemsControl
{
public class MyString
{
public string text { get; set; }
}
public class MainViewModel
{
public ObservableCollection<MyString> Strings { get; set; }
public MainViewModel()
{
Strings = new ObservableCollection<MyString>
{
new MyString{ text = "First" },
new MyString{ text = "Second" },
new MyString{ text = "Third" }
};
}
}
}
The MainWindow that uses it:
<Window x:Class="UCItemsControl.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:v="clr-namespace:UCItemsControl"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<v:MainViewModel></v:MainViewModel>
</Window.DataContext>
<Grid>
<ItemsControl
ItemsSource="{Binding Strings}" x:Name="self" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel HorizontalAlignment="Left" VerticalAlignment="Top" Orientation="Vertical" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<DataTemplate.Resources>
<Style TargetType="v:InkStringView">
<Setter Property="FontSize" Value="25"/>
<Setter Property="HorizontalAlignment" Value="Left"/>
</Style>
</DataTemplate.Resources>
<v:InkStringView TextInControl="{Binding text}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>
Your UC (no set of DataContext):
public partial class InkStringView : UserControl
{
public InkStringView()
{
InitializeComponent();
}
public String TextInControl
{
get { return (String)GetValue(TextInControlProperty); }
set { SetValue(TextInControlProperty, value); }
}
public static readonly DependencyProperty TextInControlProperty =
DependencyProperty.Register("TextInControl", typeof(String), typeof(InkStringView));
}
(Your XAML is OK)
With that I can obtain what I guess is the expected result, a list of values:
First
I am row 1
Second
I am row 1
Third
I am row 1
You need to do 2 things here (I'm assuming Strings is an ObservableCollection<string>).
1) Remove this.DataContext = new InkStringViewModel(); from the InkStringView constructor. The DataContext will be one element of the Strings ObservableCollection.
2) Change
<v:InkStringView TextInControl="{Binding text, ElementName=self}" />
to
<v:InkStringView TextInControl="{Binding }" />
The xaml you have is looking for a "Text" property on the ItemsControl to bind the value TextInControl to. The xaml I put using the DataContext (which happens to be a string) to bind TextInControl to. If Strings is actually an ObservableCollection with a string Property of SomeProperty that you want to bind to then change it to this instead.
<v:InkStringView TextInControl="{Binding SomeProperty}" />

Custom property of own UserControl needs weird binding on usage

We have a TickerUserControl with a simple Text property which stands for the displayed text of the ticker.
Do we really have to use these DependencyProperty pattern thing inside the UserControl (see below) or is there a simpler way to achieve this?
When we want to use our UserControl and BIND the text field to a property of a ViewModel we have to use the following weird binding syntax. Why can't we just use 'Text="{Binding Text}"' like all the other controls? Is there something wrong with the property implementation of the UserControl or something?
Usage of the UserControl
<userControls:TickerUserControl Text="{Binding Path=Parent.DataContext.TickerText, RelativeSource={RelativeSource Self}, Mode=OneWay}"/>
Property implementation of the UserControl (code behind)
public partial class TickerUserControl : UserControl
{
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(TickerUserControl), new PropertyMetadata(""));
// ...
}
XAML snippet of the UserControl
<UserControl x:Class="Project.UserControls.TickerUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
mc:Ignorable="d">
<TextBlock Text="{Binding Text}">
<!-- ... -->
The solution
The problem was the setting of the DataContext inside the UserControl.
I deleted the DataContext binding added a name to the UserControl and modified the TextBox binding inside the UserControl. After that I was able to bind "as usual" from outside.
<userControls:TickerUserControl Text="{Binding TickerText}"/>
<UserControl x:Class="Project.UserControls.TickerUserControl"
Name="TickerUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d">
<TextBlock Text="{Binding Text, ElementName=TickerUserControl}">
<!-- ... -->
If you want to bind your property, you'll need a dependency property.
To solve the weird binding you can do the following changes:
In your usercontrol
<UserControl Name="control"...
<TextBlock Text="{Binding Text, ElementName=control}">
And then you can bind it like that
<userControls:TickerUserControl Text="{Binding TickerText}"/>
If you want to create bindable properties in the code behind of your UserControl, then yes, you do have to use DependencyProperty objects. However, you don't have to create your bindable properties there... you could use an MVVM type pattern and create your bindable properties in a separate class as long as you set that class as the DataContext of you UserControl.
No, you don't have to use that 'weird' binding syntax... the problem is that you have hard coded setting the DataContext of your UserControl to its code behind. Instead of doing that, you can bind your Text DependencyProperty in the control like this:
<TextBlock Text="{Binding Text, RelativeSource={RelativeSource FindAncestor,
{AncestorType={x:Type Local:TickerUserControl}}}" />
Local is the XML namespace of your local project... something like this:
xmlns:Local="clr-namespace:Project.UserControls.TickerUserControl"
Then after removing the DataContext binding, you should be able to bind to the control from outside normally.

Silverlight How to create a usercontrol whose properties are customizable

I'm sure this is a real beginner question; I'm just having trouble figuring out how to search for it.
I have a simple UserControl (MyNewControl) that only has three controls, one of which is the following label:
<sdk:Label x:Name="Title" />
In another control, then, I want to use MyNewControl, like this:
<local:MyNewControl Grid.Column="1" x:Name="MyNewGuy" />
What do I need to do so that this second control can, for example, set a gradient background for my Title label?
First you define the desired dependency property in your UserControl:
public partial class MyUserControl : UserControl
{
public Brush LabelBackground
{
get { return (Brush)GetValue(LabelBackgroundProperty); }
set { SetValue(LabelBackgroundProperty, value); }
}
public static readonly DependencyProperty LabelBackgroundProperty =
DependencyProperty.Register("LabelBackground", typeof(Brush), typeof(MyUserControl), new PropertyMetadata(null));
public MyUserControl()
{
InitializeComponent();
}
}
To assign the value of your property to the child label, you can bind using the ElementName property of the binding:
<UserControl x:Class="SilverlightApplication1.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
d:DesignHeight="300"
d:DesignWidth="400"
mc:Ignorable="d"
x:Name="UserControl"
>
<Grid x:Name="LayoutRoot">
<sdk:Label x:Name="Title"
HorizontalAlignment="Center"
VerticalAlignment="Center" Content="Title" Background="{Binding LabelBackground, ElementName=UserControl}" />
</Grid>
</UserControl>
As you are using Silverlight 5, you can also set a RelativeSource to your binding, instead of internally naming your UserControl:
<sdk:Label Background="{Binding LabelBackground, RelativeSource={RelativeSource AncestorType=UserControl}}" />
Then, when using your UserControl, you just set (or bind) the LabelBackground to the desired value:
<local:MyUserControl LabelBackground="Red"/>
Just to note, you can also create a CustomControl instead of a UserControl, add the dependency property to it the same way and use a TemplateBinding when defining its template.
You can do that using dependency property in your custom control . Say you defined LableBG as an dependency property in your custom control and do the binding with an Background of your defined Label control in xaml . And when you use your custom control in another control you can set the LableBG of it from xaml or else from code behind.
Note : the type of your defined dependency property should be of Brush
For eg :
Defining Dependency Property in cs file of your custom control :
/1. Declare the dependency property as static, readonly field in your class.
public static readonly DependencyProperty LableBGProperty = DependencyProperty.Register(
"LableBG", //Property name
typeof(Brush), //Property type
typeof(MySilverlightControl), //Type of the dependency property provider
null );//Callback invoked on property value has changes
<sdk:Label x:Name="Title" Background="{Binding LableBG }" /> (Custom Control)
<local:MyNewControl Grid.Column="1" x:Name="MyNewGuy" LableBG="Red" /> (Another control)

DataTemplate in Resource sets ViewModel to View, but then

I am trying to figure the many different ways of setting datacontext of a view to a viewmodel.
One I'm oggling at this moment goes something like this:
I have my MainWindowResource:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vw="clr-namespace:DemoStuffPartII.View"
xmlns:vm="clr-namespace:DemoStuffPartII.ViewModel">
<DataTemplate DataType="{x:Type vm:PersonViewModel}">
<vw:PersonView />
</DataTemplate>
But that's also immediately where I strand. I know that I should use a ContentControl in the View. But what is the best way to configure it? How to go about this?
That is the way you can enable ViewSwitching navigation in your MVVM application.
The other missing bits are:
in the view ->
<ContentControl Content="{Binding CurrentPage}" />
in the ViewModel -> (pseudo code)
Prop ViewModelBase CurrentPage.
note however that if all u want is to connect a ViewModel to a View, you can just drop the entire DataTemplate-ContentControl thing altogether, and just do this.DataContext = new SomeViewModel(); in the codebehind.
The cleanest way I know to connect VM to Views is by using the ViewModelLocator pattern. Google ViewModelLocator.
There are a couple of simple ways to just bind a ViewModel to a view. As Elad mentioned you can add it in the code-behind:
_vm = new MarketIndexVM();
this.DataContext = _vm;
or, you can specify the ViewModel as a resource in your XAML of your view:
<UserControl.Resources>
<local:CashFlowViewModel x:Key="ViewModel"/>
<Converters:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</UserControl.Resources>
and bind the DataContext of your LayoutRoot to that resource:
<Grid x:Name="LayoutRoot" DataContext="{StaticResource ViewModel}">
Maybe this doesn't directly answer your question, but have you looked at using an MVVM framework? For example, in Caliburn.Micro you would do (very basic example):
public class ShellViewModel : Conductor<IScreen>
{
public ShellViewModel()
{
var myViewModel = new MyViewModel();
this.ActivateItem(myViewModel);
}
}
ShellView.xaml
<Grid>
<ContentControl x:Name="ActiveItem" />
</Grid>
MyView.xaml
<Grid>
<TextBlock>Hello world</TextBlock>
</Grid>
This is a viewmodel first approach.

Resources