Assign a DataContext to XAML, pointing to its code behind the class

I am developing a Windows Phone 8 application using User Control.

In this user control, I want to make a datacontext in XAML, pointing to its code. Now I do this on the constructor:

public CustomOptionButton()
{
    InitializeComponent();

    LayoutRoot.DataContext = this;
}

But, How can I do this on XAML?

+3
source share
2 answers

Try the following:

<UserControl Name="LayoutRoot" 
             DataContext="{Binding RelativeSource={RelativeSource Self}}" ... />

or

<UserControl.DataContext>
    <local:TestViewModel />
</UserControl.DataContext>

or

<UserControl.Resources>
    <local:MyViewModel x:Key="TestViewModel" />
</UserControl.Resources>

<UserControl.DataContext>
    <Binding Source="{StaticResource TestViewModel}" />
</UserControl.DataContext>
+2
source

when I use the current datacontext in my user controls, this is what I do:

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
d:DataContext="{Binding}"

EDIT

As @WiredPrairie pointed out that I misunderstood the question, so this is an easier way and alternative to what @AnatoliyNikolaev has to offer

x:Name="_this">  
<Grid x:Name="LayoutRoot" DataContext="{Binding ElementName=_this}">
+1
source

All Articles