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.
CodePudding user response:
You can do it this way:
MainWindow.xaml
<Grid>
<Grid.Resources>
<CommandBarFlyout
x:Name="TestCommanBarFlyout"
Placement="Right">
<AppBarButton Icon="Copy" />
<AppBarButton Icon="Delete" />
</CommandBarFlyout>
</Grid.Resources>
<TreeView ItemsSource="{x:Bind Items}">
<TreeView.ItemTemplate>
<DataTemplate x:DataType="x:String">
<TreeViewItem
Content="{x:Bind}"
ContextRequested="TreeViewItem_ContextRequested" />
</DataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
MainWindow.xaml.cs
public ObservableCollection<string> Items { get; } = new() { "A", "B", "C" };
private void TreeViewItem_ContextRequested(UIElement sender, ContextRequestedEventArgs args)
{
if (sender is TreeViewItem item)
{
item.IsSelected = true;
TestCommanBarFlyout.ShowAt(
item,
new FlyoutShowOptions()
{
ShowMode = FlyoutShowMode.Standard
});
}
}