WinUI 3 TreeView - How to set selected node on right click

Daniel Parker 46 Reputation points
2022-10-20T18:28:10.543+00:00

I am trying to show a MenuFlyout on a WinUI 3 TreeView when the user right clicks on a node, and allow them to choose an action that applies to the node. Single node selection is in effect, and the node is not automatically selected on a right click.

After searching, I came across this answer, but it doesn't work with WinUI 3, because the WinUI 3 TreeView control does not have a GetNodeAt method, I don't see how to get a TreeViewNode from a point.

Any suggestions? Thanks.

Windows App SDK
Windows App SDK
A set of Microsoft open-source libraries, frameworks, components, and tools to be used in apps to access Windows platform functionality on many versions of Windows. Previously known as Project Reunion.
787 questions
0 comments No comments
{count} votes

Accepted answer
  1. Castorix31 85,211 Reputation points
    2022-10-21T01:52:03.253+00:00

    You can use PointerPressed event.
    A quick test with a TreeView from WinUI3 Gallery and a simple MenuFlyout from the TreeViewNode text, to be improved :

        private void Tv1_PointerPressed(object sender, PointerRoutedEventArgs e)  
        {  
            var properties = e.GetCurrentPoint((UIElement)sender).Properties;  
            if (properties.IsRightButtonPressed)  
            {  
                var dc = ((FrameworkElement)e.OriginalSource).DataContext;  
                MenuFlyout mf = new MenuFlyout();  
                MenuFlyoutItem mfi = new MenuFlyoutItem();  
                mfi.Text = ((TreeViewNode)dc).Content.ToString();  
                mf.Items.Add(mfi);  
                Microsoft.UI.Input.PointerPoint pp = e.GetCurrentPoint((UIElement)sender);  
                Point ptElement = new Point(pp.Position.X, pp.Position.Y);  
                mf.ShowAt((FrameworkElement)sender, ptElement);    
            }  
        }  
    

    252764-winui3-treeview-rightclick.gif

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.