JMan
JMan

Reputation: 2629

Proper way to assign and work with WPF DataContext in Resources

My application needs to open a UserControl that needs to have a parameter/property to contain a year. For this year i will have my control show some edit values.

I'm running into the problem that my Window.Resource section i have declared has a contextmenu that i'm attching to a Gridview. From this contextmenu in the resource i cannot bind directly to my Commands on my ViewModel.

I solved this problem by adding my ViewModel as a StaticResource in my Xaml. Unfortunatly this cause my xaml to generate my ViewModel and it's impossible for me to pass my parameter or property 'year' and when i'm retrieving my data it is done for the year=0.

Is there a way to replace the viewmodel binding i have provided for my contextmenu so it can access the viewmodel i have set in code?

<UserControl.Resources>
    <vm:ViewModel x:Key="viewModel" />

    <ribbon:ContextMenu x:Key="MyContextMenu"
                         x:Shared="False"
                         Placement="MousePoint" >
        <ribbon:Menu Focusable="false">
            <ribbon:Button 
                Command="{Binding Source={StaticResource viewModel}, Path=MyCommand}"
                Label="MyLabel"/>
        </ribbon:Menu>
    </ribbon:ContextMenu>

</UserControl.Resources>

Upvotes: 2

Views: 2239

Answers (1)

Florian Gl
Florian Gl

Reputation: 6014

Yes this it possible. You could create a dummy-class which holds the DataContext:

public class Proxy:DependencyObject
{
    public static readonly DependencyProperty DataProperty = DependencyProperty.Register("Data", typeof(object), typeof(Proxy));
    public object Data 
    {
        get { return this.GetValue(DataProperty); }
        set { this.SetValue(DataProperty, value); }
    }
}

refer to it in the resources and bind the DataContext to its Data-property:

<UserControl.Resources>
    <local:Proxy x:Key="proxy" Data="{Binding}"/>
</UserControl.Resources>

Now the Data Property holds your ViewModel and you can bind to it like so:

<ribbon:ContextMenu x:Key="MyContextMenu"
                     x:Shared="False"
                     Placement="MousePoint" >
    <ribbon:Menu Focusable="false">
        <ribbon:Button 
            Command="{Binding Source={StaticResource proxy}, Path=Data.MyCommand}"
            Label="MyLabel"/>
    </ribbon:Menu>
</ribbon:ContextMenu>

Upvotes: 3

Related Questions