.NET MAUI 7中ListView的MenuItem CommandParameter绑定异常
问题描述
在MAUI项目中,ListView的ViewCell.ContextActions嵌套的MenuItem使用CommandParameter="{Binding .}"(或{Binding})时,命令执行时参数始终为null,该问题与StackOverflow上的《MenuItem + CommandParameter = null ! Why?》场景一致。
问题原因
原代码中将x:DataType="model:Ingredient"设置在ViewCell内部的StackLayout上,导致ViewCell的ContextActions区域(包含MenuItem)的绑定上下文没有正确继承到当前的Ingredient对象,MAUI绑定系统无法正确解析CommandParameter的绑定目标。
解决方案
将x:DataType="model:Ingredient"移动到DataTemplate节点上,让整个ItemTemplate的绑定上下文都明确指向Ingredient类型,确保MenuItem的CommandParameter能正确绑定到当前列表项的Ingredient对象。
修改后的视图代码
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:viewmodel="clr-namespace:CookUs.ViewModel" xmlns:model="clr-namespace:CookUs.Model" x:Class="CookUs.View.ViewRecipePage" x:DataType="viewmodel:ViewRecipeViewModel" Title="{Binding Recipe.Name}"> <ScrollView> <VerticalStackLayout> <ListView ItemsSource="{Binding Recipe.Ingredients}" x:Name="listView"> <ListView.ItemTemplate> <!-- 将x:DataType移到DataTemplate上 --> <DataTemplate x:DataType="model:Ingredient"> <ViewCell> <ViewCell.ContextActions> <MenuItem Text="Add to Cart" IconImageSource="add_to_cart.png" Command="{Binding Source={x:Reference listView}, Path=BindingContext.AddToCartCommand}" CommandParameter="{Binding}" /> </ViewCell.ContextActions> <StackLayout> <Label Text="{Binding Name}" FontAttributes="Bold" FontSize="Small" HorizontalTextAlignment="Center"/> <Label Text="{Binding Quantity}" FontSize="Micro" HorizontalTextAlignment="Center"/> </StackLayout> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView> </VerticalStackLayout> </ScrollView>
说明
- 视图模型和模型代码无需修改,保持原有逻辑即可。
- 修改后,MenuItem的CommandParameter会正确传递当前列表项的Ingredient实例,命令执行时
obj参数不再为null。
内容的提问来源于stack exchange,提问作者user20564490
相关产品推荐
相关产品推荐

