Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do DataContext assign on XAML pointing to its code behind class

I'm developing a Windows Phone 8 application with a User Control.

On this user control, I want to do the datacontext on XAML pointing to its codebehind. Now I'm doing it on the constructor:

public CustomOptionButton()
{
    InitializeComponent();

    LayoutRoot.DataContext = this;
}

But, How can I do it on XAML?

like image 386
VansFannel Avatar asked Nov 28 '25 06:11

VansFannel


1 Answers

Try this:

<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>
like image 137
Anatoliy Nikolaev Avatar answered Nov 29 '25 22:11

Anatoliy Nikolaev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!