WinUI3中如何实现右键点击XAML里的Image弹出CommandBarFlyout?
解决WinUI中Image右键菜单不弹出的问题
你的代码存在几处导致右键菜单无法正常触发的问题,以下是具体修正方案:
问题分析
- 绑定方式错误:你使用
{x:Bind}绑定ContextFlyout,但DeleteCommandsFlyout定义在Grid的资源字典中,x:Bind默认绑定页面级属性,无法正确引用资源字典内的元素,应改用{StaticResource}。 - 冗余属性冲突:同时设置
FlyoutBase.AttachedFlyout和ContextFlyout会引发冲突——ContextFlyout是WinUI专门用于右键上下文菜单的属性,而AttachedFlyout需要手动调用ShowAt触发,无需同时配置。 - 资源标识错误:资源字典中的元素需用
x:Key标识,而非x:Name,否则无法被StaticResource正确识别。
修正后的代码
<winex:WindowEx xmlns:winex="using:WinUIEx" x:Class="myapp.ViewImagesWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" > <Grid> <Grid.RowDefinitions> <RowDefinition Height="150" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Grid Grid.Row="0"> <Grid.ColumnDefinitions> <ColumnDefinition Width="50*" /> <ColumnDefinition Width="50*" /> <ColumnDefinition Width="50*" /> <ColumnDefinition Width="50*" /> </Grid.ColumnDefinitions> <Grid.Resources> <CommandBarFlyout x:Key="DeleteCommandsFlyout"> <CommandBarFlyout.SecondaryCommands> <AppBarButton Label="Delete" Icon="Delete" ToolTipService.ToolTip="Delete" Click="DeleteAppBarButton_Click"/> </CommandBarFlyout.SecondaryCommands> </CommandBarFlyout> </Grid.Resources> <Image x:Name="image1" Tapped="Image_Tapped" Grid.Column="0" Source="ms-appx:///Assets/StoreLogo.scale-400.png" Width="100" Height="150" Margin="5" Stretch="Uniform" RightTapped="image1_RightTapped" /> <Image x:Name="image2" Tapped="Image_Tapped" Grid.Column="1" Source="ms-appx:///Assets/StoreLogo.scale-400.png" Width="100" Height="150" Margin="5" Stretch="Uniform" ContextFlyout="{StaticResource DeleteCommandsFlyout}"/> <Image x:Name="image3" Tapped="Image_Tapped" Grid.Column="2" Source="ms-appx:///Assets/StoreLogo.scale-400.png" Width="100" Height="150" Margin="5" Stretch="Uniform" ContextFlyout="{StaticResource DeleteCommandsFlyout}"/> <Image x:Name="image4" Tapped="Image_Tapped" Grid.Column="3" Source="ms-appx:///Assets/StoreLogo.scale-400.png" Width="100" Height="150" Margin="5" Stretch="Uniform" ContextFlyout="{StaticResource DeleteCommandsFlyout}"/> </Grid> <!-- Large image view --> <Image Grid.Row="1" x:Name="largeImage" Source="ms-appx:///Assets/StoreLogo.scale-400.png" Stretch="Uniform" Margin="10" /> </Grid> </winex:WindowEx>
关键改动说明
- 将
CommandBarFlyout的x:Name改为x:Key="DeleteCommandsFlyout":资源字典内的元素必须通过x:Key标识,才能被StaticResource正确引用。 - 移除
FlyoutBase.AttachedFlyout属性,仅保留ContextFlyout="{StaticResource DeleteCommandsFlyout}":ContextFlyout会自动响应右键点击事件,无需额外触发逻辑。 - 使用
{StaticResource}替代{x:Bind}:正确引用Grid资源字典中的菜单实例。
内容的提问来源于stack exchange,提问作者Ethan Allen
相关产品推荐
相关产品推荐

