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

迁移至VS2022后Xamarin.Forms出现方法签名匹配错误,求助解决

迁移VS2022后Xamarin.Forms项目的Completed事件与空引用问题解决

问题现象

迁移至Visual Studio 2022后,Xamarin.Forms项目出现两类异常:

  1. 编译/运行时提示 No method txtUserName_Completed with correct signature found on type
  2. 移除Entry控件的Completed绑定后,触发Object reference not set to an instance of an object空引用异常,错误定位到xaml.g.cs的LoadFromXaml方法行。已尝试重启VS、清理解决方案、删除bin/obj文件夹,问题未解决。

代码问题分析

1. Completed事件找不到的潜在原因

后台代码中txtUserName_Completed、txtPassword_Completed的签名符合Xamarin.Forms事件要求,但存在编译配置或缓存问题:

  • 后台类虽为partial,但未启用强制XAML编译
  • 编译缓存导致XAML与后台类的事件绑定未同步

2. 空引用异常的根源

后台代码中CurrentContext属性存在类型转换错误:

private InvoicesViewModel CurrentContext { get { return (InvoicesViewModel)BindingContext; } }

而XAML中明确绑定的是LoginViewModel:

<ContentPage.BindingContext>
    <vms:LoginViewModel />
</ContentPage.BindingContext>

强制转换类型不匹配会返回null,后续任何访问CurrentContext的操作都会触发空引用异常。

修复步骤

修复Completed事件找不到的问题

  • 启用强制XAML编译:取消注释后台类的[XamlCompilation(XamlCompilationOptions.Compile)]特性,避免运行时解析XAML的延迟问题
  • 调整方法访问修饰符:将public改为private(XAML事件绑定支持私有方法,减少不必要的公开成员)
  • 重新生成解决方案:右键解决方案选择「重新生成」,彻底清理编译缓存

修复空引用异常

  • 修正CurrentContext的类型转换:将InvoicesViewModel改为LoginViewModel,或直接移除该冗余属性,在需要的地方直接使用BindingContext as LoginViewModel
  • 给控件引用添加空值保护:在访问txtUserName.Text、txtPassword.Text时使用空值运算符?.,避免控件未初始化导致的空引用

完整修复后的后台代码

using MobileApp.UI.ViewModels;
using System;
using Xamarin.Forms;

namespace MobileApp.UI.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class LoginPage : ContentPage
    {
        private LoginViewModel CurrentContext => (LoginViewModel)BindingContext;

        public LoginPage()
        {
            InitializeComponent();
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();
        }

        private void txtUserName_Completed(object sender, EventArgs e)
        {
            ChkIfCanLogin();
        }

        private void txtPassword_Completed(object sender, EventArgs e)
        {
            ChkIfCanLogin();
        }        

        private void ChkIfCanLogin()
        {
            if (!string.IsNullOrWhiteSpace(txtUserName?.Text) &&
                !string.IsNullOrWhiteSpace(txtPassword?.Text))
            {
                CurrentContext?.LoginCommand?.Execute(null);
            }
        }
    }
}

额外排查建议

  • 删除项目根目录下的.vs隐藏文件夹,彻底清理VS缓存后重启
  • 检查Xamarin.Forms版本:确保VS2022中使用的版本与项目兼容,必要时升级至最新稳定版
  • 验证XAML的x:Class属性与后台类的命名空间、类名完全一致,无拼写错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 09:08:14