C# MAUI中CollectionView命令传参Debug/Release结果不一致问题
问题:MAUI Release模式下CollectionView项传递给VM命令时参数为Null
我的目标是将CollectionView选中项的句柄传递给MainPageVM.CVItemButton()方法。Debug模式下传递的句柄不为空且能正常工作,但Release模式下该句柄为Null。
设计此结构的原因是为了将CollectionViewItem与其具体使用场景分离,以便为其单独设置命令。当然也可以不使用SelfHandle,但我不知道如何将项句柄传递给命令,若有更优的传参方式,请告知我。
测试环境:VS 2022、MAUI框架、搭配CommunityToolkit.Mvvm模块
关键代码
1. MainPage.xaml(构建CollectionView,传递项句柄到SelfHandle)
<CollectionView HorizontalOptions="Center" ItemsLayout="VerticalGrid" ItemsSource="{Binding CVItems}" SelectionMode="None"> <CollectionView.ItemTemplate> <DataTemplate> <local:CollectionViewItem HorizontalOptions="Center" Button1Command="{Binding CVItemButtonCommand, Source={RelativeSource AncestorType={x:Type local:MainPageVM}}}" SelfHandle="{Binding}" BindingContext="{Binding}" /> </DataTemplate> </CollectionView.ItemTemplate> </CollectionView>
2. MainPageVM.cs(创建命令与数据)
public partial class MainPageVM : ObservableObject { public MainPageVM() { CVItems = new() { new (){ Value = 1}, }; } [ObservableProperty] private ObservableCollection<CollectionViewItemModel> _CVItems; [ObservableProperty] private string _Result; [RelayCommand(CanExecute = nameof(CanCVItemButton))] private void CVItemButton(CollectionViewItemModel m) { Trace.WriteLine($"Parameter shouldn't be NULL, in Debug it's not NULL, but in Release it's NULL"); Result = ($"CVItemButton() Paramter is NULL => {m == null}"); } private bool CanCVItemButton(CollectionViewItemModel m) { Trace.WriteLine($"CanCVItemButton() received an NULL parameter => {m == null}"); return true; } }
3. CollectionViewItem.cs(定义绑定属性)
public partial class CollectionViewItem : ContentView { public static readonly BindableProperty Button1CommandProperty = BindableProperty.Create(nameof(Button1Command), typeof(ICommand), typeof(CollectionViewItem), null, BindingMode.OneWay); public ICommand Button1Command { get => (ICommand)GetValue(Button1CommandProperty); set => SetValue(Button1CommandProperty, value); } public static readonly BindableProperty SelfHandleProperty = BindableProperty.Create(nameof(SelfHandle), typeof(CollectionViewItemModel), typeof(CollectionViewItem), null, BindingMode.TwoWay); public CollectionViewItemModel SelfHandle { get => (CollectionViewItemModel)GetValue(SelfHandleProperty); set => SetValue(SelfHandleProperty, value); } public CollectionViewItem() { InitializeComponent(); } }
4. CollectionViewItem.xaml(按钮命令绑定)
<?xml version="1.0" encoding="utf-8" ?> <ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MauiApp1.CollectionViewItem" x:Name="root"> <HorizontalStackLayout> <Button Text="Button" Command="{Binding Button1Command, Source={x:Reference root}}" CommandParameter="{Binding SelfHandle, Source={x:Reference root}}" /> </HorizontalStackLayout> </ContentView>
内容的提问来源于stack exchange,提问作者ss1969
相关产品推荐
相关产品推荐

