Milleu Milleu - 1 year ago 115
C# Question

Bind MenuItems Command to UserControls DataContext

I have the following Layout:

public class ParentUserControl : UserControl{...}

DataContext={Binding MyViewModel ....}
<TreeView ...>
.... >
<MenuItem Header="item"
Command="{Binding DataContext.SomeCommandInMyViewModel,
AncestorType={x:Type ParentUserControl}}}"/>
<TextBlock Text="{Binding Path=Name}"/>

Im trying to call a command of the UserControls ViewModel from within the Context of a TreeViewItem with no success. It tells me ParentUserControl Is not supported in a wpf Project. If I change AncestorType to UserControl the Command does not get called. Is there something I miss?

Sam Sam
Answer Source

This is because ContextMenu is not a part of the visual tree. The simplest way without changing code-behind is this:

Give a name to ParentUserControl:

<ParentNameSpace:ParentUserControl x:Name="ParentRoot" ... >

Use this binding:

Command="{Binding Source={x:Reference Name=ParentRoot}, Path=DataContext.SomeCommandInMyViewModel}"

Update for using without x:Name attribute.

You can use ContextMenu.PlacementTarget property, which will point to StackPanel in your case. Then you can use it's Tag property for accessing your view-model.

<StackPanel Tag="{Binding RelativeSource={RelativeSource AncestorType=ParentNameSpace:ParentUserControl}, Path=DataContext}">

And command:

Command="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.Tag.SomeCommandInMyViewModel}"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download