Milleu
Milleu

Reputation: 159

Bind MenuItems Command to UserControls DataContext

I have the following Layout:

public class ParentUserControl : UserControl{...}

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

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?

Upvotes: 1

Views: 584

Answers (1)

Sam
Sam

Reputation: 1424

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}"

Upvotes: 1

Related Questions