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

MAUI中无法传递绑定的PhotoItemViewModel作为命令参数问题

解决MAUI中TouchBehavior长按命令参数为null的问题

问题出在TouchBehavior的LongPressCommand绑定写法错误,导致命令参数无法正确传递当前的PhotoItemViewModel实例。

修正步骤:

  • 修正命令绑定格式:移除Binding表达式内的x:DataType=ContentPage,正确的绑定应该通过Source指定页面实例,再绑定到页面ViewModel的命令:
    <Image.Behaviors>
        <toolkit:TouchBehavior
            LongPressCommand="{Binding Source={x:Reference Page}, Path=BindingContext.LongPressCommand}"
            LongPressCommandParameter="{Binding .}"/>
    </Image.Behaviors>
    
  • 确认命令定义正确:确保页面ViewModel中的LongPressCommand是带泛型参数的RelayCommand(基于CommunityToolkit.Mvvm):
    public ICommand LongPressCommand { get; }
    
    public YourPageViewModel()
    {
        LongPressCommand = new RelayCommand<PhotoItemViewModel>(OnPhotoLongPressed);
    }
    
    private void OnPhotoLongPressed(PhotoItemViewModel photo)
    {
        IsSelectionMode = true;
        photo.IsSelected = true;
    }
    

原因说明:

在DataTemplate内部已经通过x:DataType="data:PhotoItemViewModel"指定了当前上下文类型,若在绑定外部命令时错误地在Binding标签内添加x:DataType=ContentPage,会强制覆盖当前上下文,导致{Binding .}无法指向当前的PhotoItemViewModel实例,最终传递给命令的参数为null。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 17:28:18