Binding Context menu commands to ViewModel which is not in context Visuals tree

大兔子大兔子 提交于 2019-12-08 13:52:12

问题


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>


来源:https://stackoverflow.com/questions/18841208/binding-context-menu-commands-to-viewmodel-which-is-not-in-context-visuals-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!