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

使用Community Toolkit TouchBehavior运行时崩溃,报Arg_NoDefCtor错误

解决 CommunityToolkit.Maui TouchBehavior 无参构造函数缺失错误

错误根源:CommunityToolkit.Maui 11.x版本中 TouchBehavior 已移除无参构造函数,空项目能运行是因为自动完成了依赖初始化,而多项目结构中缺少必要配置或初始化步骤。

以下是针对性解决步骤:

1. 统一多项目的Toolkit依赖与初始化

  • 确保**所有引用Toolkit的项目(App项目、类库等)**都安装了版本一致的 CommunityToolkit.Maui NuGet包(11.2.0)。
  • 在 MauiProgram.cs 中必须添加Toolkit初始化代码:
using CommunityToolkit.Maui;

var builder = MauiApp.CreateBuilder();
builder
    .UseMauiApp<App>()
    .UseMauiCommunityToolkit(); // 这一行不可省略

2. 修正XAML中TouchBehavior的使用

由于无参构造函数被移除,需调整使用方式:

方式一:绑定Command(推荐)

直接通过Command处理触摸逻辑,无需x:Name:

<StackLayout.Behaviors>
    <toolkit:TouchBehavior
        Command="{Binding TouchCommand}"
        CommandParameter="YourParameter"/>
</StackLayout.Behaviors>

ViewModel中对应实现:

public ICommand TouchCommand { get; }

public YourViewModel()
{
    TouchCommand = new Command<string>(ExecuteTouch);
}

private void ExecuteTouch(string parameter)
{
    // 编写触摸处理逻辑
}

方式二:代码后台实例化

如果需要使用x:Name,在页面构造函数中手动添加Behavior:

using CommunityToolkit.Maui.Behaviors;

public YourPage()
{
    InitializeComponent();
    var touchBehavior = new TouchBehavior();
    // 绑定事件,例如 touchBehavior.TouchStarted += OnTouchStarted;
    testStackLayout.Behaviors.Add(touchBehavior);
}

XAML中移除原TouchBehavior声明,给StackLayout添加x:Name:

<StackLayout x:Name="testStackLayout"
    BackgroundColor="{DynamicResource Primary}"
    Orientation="Horizontal"
    HeightRequest="{OnPlatform iOS=50, Android=60}"
    Margin="0,30,0,0"
    Padding="40,0,0,0">
    <!-- 原有Label内容 -->
</StackLayout>

3. 清理重建解决方案

多项目结构易出现缓存或版本不一致问题:

  • 删除所有项目的bin、obj文件夹
  • 执行清理解决方案 -> 生成解决方案,确保全项目编译通过

4. 检查目标框架一致性

确认所有项目的目标框架均为.NET 9,避免框架版本差异导致依赖加载失败。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 13:05:20