0

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

WAQ
  • 2,556
  • 6
  • 45
  • 86

1 Answers1

5

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>
Nitin
  • 18,344
  • 2
  • 36
  • 53
  • I dont want to change source of TreeView. I just want to handle Context Menu's events in ViewModel – WAQ Sep 17 '13 at 04:41
  • I did get my VieeModel's fired with this. But now how Do I know for which Item the command was called? I dont seem to get that anywhere :s – WAQ Sep 17 '13 at 04:58
  • so instead of putting context menu on the whole treeview.. try putting the context menu on the treeviewitem..define it in style of treeviewitem.. then you can send item in command parameter like Binding=PlacementTarget.DataContext – Nitin Sep 17 '13 at 05:09
  • 1
    I put it in the TreeViewItems style. Does not seem to work :s The command is not getting called – WAQ Sep 18 '13 at 16:12