CommunityToolkit.Maui TouchBehavior参数异常:CommandParameter始终传Null
CommunityToolkit.Maui TouchBehavior 参数传递异常问题
TouchBehavior.CommandParameter 和 TouchBehavior.LongPressCommandParameter 始终以 null 值传递给对应的Command和LongPressCommand。
在以下示例中,点击CollectionView中的项时,提示框始终只显示Selected value:,因为CommandParameter始终为null。正常情况下点击Item 1时,应显示Selected value: Item 1。

XAML 代码示例
<VerticalStackLayout Padding="30,0" Spacing="25"> <Label Text="{Binding Title}" Style="{StaticResource Headline}" SemanticProperties.HeadingLevel="Level1" /> <Label Text="点击或长按项目无法正确将该项目作为CommandParameter或LongTouchCommandParameter传递。" Style="{StaticResource SubHeadline}" SemanticProperties.HeadingLevel="Level1" /> <CollectionView x:Name="collectionView" ItemsSource="{Binding Items}"> <CollectionView.ItemTemplate> <DataTemplate x:DataType="{x:Type x:String}"> <Label Padding="10" Text="{Binding .}" x:Name="Label"> <Label.Behaviors> <toolkit:TouchBehavior Command="{Binding Source={x:Reference collectionView}, Path=BindingContext.ShowItemCommand}" CommandParameter="{Binding .}" LongPressCommand="{Binding Source={x:Reference collectionView}, Path=BindingContext.ShowItemCommand}" LongPressCommandParameter="{Binding .}" <!-- CommunityToolkit.Maui的TouchBehavior中,CommandParameter和LongPressCommandParameter始终传递为null。 而Maui.TouchEffect组件不存在此问题 --> </Label.Behaviors> </Label> </DataTemplate> </CollectionView.ItemTemplate> </CollectionView> </VerticalStackLayout>
C# ViewModel 代码示例
public partial class MainViewModel : ObservableObject { public string Title => "Hello, Maui!"; public ObservableCollection<string> Items { get; set; } = ["Item 1", "Item 2", "Item 3"]; /// <summary> /// item参数始终为null。Maui.TouchEffect组件不存在此问题 /// </summary> /// <param name="item"></param> /// <returns></returns> [RelayCommand] private Task ShowItem(string item) => Application.Current.MainPage.DisplayAlert($"Selected value:", item, "OK"); }
复现说明
已提供完整的复现项目用于验证该问题。
内容的提问来源于stack exchange,提问作者Brandon Minnick
相关产品推荐
相关产品推荐

