我的问题与此类似MenuItem + CommandParameter = null ! Why?
我的MenuItem
中的CommandParameter="{Binding .}"
嵌套在ViewCell.ContextActions
中,当我读取它时,它总是为空。
下面是完整的代码:
查看
<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>
<DataTemplate>
<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 x:DataType="model:Ingredient">
<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>
视图模型
public Command AddToCartCommand { get; }
public ViewRecipeViewModel()
{
AddToCartCommand = new Command(OnAddToCartAsync);
}
private async void OnAddToCartAsync(object obj)
{
if (obj == null) return;
Ingredient i = obj as Ingredient;
if(!(await DataStore.AddToCartAsync(i))) {
await Application.Current.MainPage.DisplayAlert("Error", "Failed to add to cart", "OK");
}
OnPropertyChanged(nameof(Cart));
}
型号
namespace CookUs.Model
{
public class Ingredient
{
public string Name { get; set; }
public string Quantity { get; set; }
}
}
1条答案
按热度按时间hjzp0vay1#
更新
您的问题是
x:DataType
。当使用编译绑定时,您需要在BindingContext更改的任何地方设置正确的DataType。在这种情况下,您需要在DataTemplate
上添加x:DataType="Ingredient"
,而不是StackLayout
:来自以前版本的答案:
注意绑定中的
.
:CommandParameter="{Binding .}"
它意味着将整个项作为参数传递。