How to mimic left click behaviour for right click

2019-08-20 02:42发布

When I left click on a TreeView, it automatically selects the item under mouse. How can I do this for right click so when you right click, it also selects the item under mouse?

I want to do this because when I right click, I set the context menu of the TreeView when the SelectedItem changes, based on the e.NewValue of TreeView_SelectedItemChanged. But the right click itself doesn't change the SelectedItem, that's why the wrong menu shows up. Or I have to first left click to the item I want selected, and then right click.

Any ideas on how to do this?

2条回答
相关推荐>>
2楼-- · 2019-08-20 03:14

The accpeted answer is correct about using the mouse down event, but are you sure you need Visual Tree Helper and Hit Testing? You might try something like:

var parent = this.DataContext as Parent;
var clicked = (sender as FrameworkElement).DataContext as Child;
parent.SelectedChild = clicked;

Remember, you can usually get to your viewmodel objects as the DataContext of a FrameworkElement. Using the Visual Tree and Hit Testing doesn't come up often.

查看更多
叼着烟拽天下
3楼-- · 2019-08-20 03:23

Override the right click event. Here is an example to do it.

查看更多
登录 后发表回答