Binding Context menu commands to ViewModel which i

2019-06-14 11:42发布

问题:

I have a treeView whose itemsource is a collection of my Model class. I have added a context menu on the treeView. Since the commands of the contextMenu should be in the visual tree, so I had to place them in my Model class. Which is wrong (Binding directory to the Model).

How can I Bind my context menu's Command to my ViewModel rather than Model?

Thanks

回答1:

You need not to place commands in model. Here you can access your commands in ViewModel like below: Here Tag will contain the Binding to ViewModel and can be used to access the command.

    <TreeView Tag="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"
      <TreeView.ContextMenu>
        <ContextMenu>
            <MenuItem Header="MyCommand" 
                     CommandParameter="{Binding }"
                     Command="{Binding Path=PlacementTarget.Tag.DataContext.MyCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"/>
        </ContextMenu>
      </TreeView.ContextMenu>
    </TreeView>