Select TreeView Node on right click before displaying ContextMenu

后端 未结 11 2008
鱼传尺愫
鱼传尺愫 2020-11-29 19:39

I would like to select a WPF TreeView Node on right click, right before the ContextMenu displayed.

For WinForms I could use code like this Find node clicked under co

11条回答
  •  旧巷少年郎
    2020-11-29 20:08

    I was having a problem with selecting children with a HierarchicalDataTemplate method. If I selected the child of a node it would somehow select the root parent of that child. I found out that the MouseRightButtonDown event would get called for every level the child was. For example if you have a tree something like this:

    Item 1
       - Child 1
       - Child 2
          - Subitem1
          - Subitem2

    If I selected Subitem2 the event would fire three times and item 1 would be selected. I solved this with a boolean and an asynchronous call.

    private bool isFirstTime = false;
        protected void TaskTreeView_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            var item = sender as TreeViewItem;
            if (item != null && isFirstTime == false)
            {
                item.Focus();
                isFirstTime = true;
                ResetRightClickAsync();
            }
        }
    
        private async void ResetRightClickAsync()
        {
            isFirstTime = await SetFirstTimeToFalse();
        }
    
        private async Task SetFirstTimeToFalse()
        {
            return await Task.Factory.StartNew(() => { Thread.Sleep(3000); return false; });
        }
    

    It feels a little cludgy but basically I set the boolean to true on the first pass through and have it reset on another thread in a few seconds (3 in this case). This means that the next passes through where it would try to move up the tree will get skipped leaving you with the correct node selected. It seems to work so far :-)

提交回复
热议问题