开发者

How to mimic left click behaviour for right click for a TreeView in WPF?

开发者 https://www.devze.com 2023-02-27 11: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?

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. Bu开发者_JS百科t 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?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消