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

1
  • can you share your xaml code? Commented Sep 17, 2013 at 4:29

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

4 Comments

I dont want to change source of TreeView. I just want to handle Context Menu's events in ViewModel
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
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
I put it in the TreeViewItems style. Does not seem to work :s The command is not getting called

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.