You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Xamarin UWP应用的列表项中添加上下文菜单并解决相关报错

Xamarin UWP ListView 列表项添加上下文菜单解决方案

错误原因分析

  • 第一种方案报错:MenuFlyout 是 UWP 平台原生控件,不属于 Xamarin.Forms 共享层控件集,直接在共享项目的 XAML 中声明会找不到对应类型。
  • 第二种方案报错:ContextActions 是 ViewCell 的内置属性,你错误地将它写在了 ViewCell 闭合标签的外部,导致 XAML 解析器无法识别该属性归属。

正确实现代码

Xamarin.Forms 官方提供了跨平台的 ViewCell.ContextActions 作为列表项上下文菜单实现,只需将属性声明移到 ViewCell 标签内部即可:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:GraphTutorial.ContextMenu"  
         Title="Shared Document Library"
         x:Class="GraphTutorial.SPDocumentLibraryContentsPage">
    <ListView x:Name="SharedDocumentList"
              HasUnevenRows="true"
              Margin="10,10,10,10"
              ItemSelected="OnItemSelected">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <!-- ContextActions 放在 ViewCell 标签内部 -->
                    <ViewCell.ContextActions>
                        <MenuItem Text="Add" Clicked="Add_Clicked"/>
                        <MenuItem Text="Delete" Clicked="Delete_Clicked"/>
                        <MenuItem Text="Edit" Clicked="Edit_Clicked"/>
                    </ViewCell.ContextActions>
                    <StackLayout Margin="10,10,10,10">
                        <Label Text="{Binding Path=Id}"
                               FontAttributes="Bold"
                               FontSize="Medium" />
                        <Label Text="{Binding Path=WebUrl}"
                               FontSize="Small" />
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>

适配说明

  • 该实现默认在 UWP 平台上右键点击列表项即可呼出上下文菜单,其他平台也会自动适配对应交互(iOS 左划、Android 长按)。
  • 如果需要 UWP 专属的自定义菜单样式,可以通过 Xamarin.Forms 平台特定 API 或者自定义渲染器扩展,无需引入原生 UWP 控件到共享层。

内容的提问来源于stack exchange,提问作者dot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 21:45:04