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

从Xamarin.Forms迁移至MAUI后MessagingCenter上下文不存在问题

迁移至MAUI后MessagingCenter找不到的问题解决

问题背景

在Xamarin.Forms项目中使用MessagingCenter实现组件间通信,迁移到Microsoft.Maui.Essentials后出现编译错误:
The name 'MessagingCenter' does not exist in the current context

相关代码

MyViewController.cs:

MessagingCenter.Subscribe<Game1>(this, "Hi", (sender) =>
{
    G_RemoveLogoTestMyView();
});

public void G_RemoveLogoTestMyView()
{
    //remove image
    var LogoView = View.ViewWithTag(1234);
    if (null != LogoView)
        LogoView.RemoveFromSuperview();
}

Game1.cs:

MessagingCenter.Send<Game1>(this, "Hi");

解答

在Microsoft.Maui中仍可使用MessagingCenter,但它不属于Microsoft.Maui.Essentials组件,而是归属在Microsoft.Maui.Controls命名空间下。你遇到的错误是因为代码文件缺少该命名空间的引用,添加using Microsoft.Maui.Controls;后即可解决问题,这和你补充的验证结果一致。

额外说明:虽然MessagingCenter能继续使用,但MAUI官方更推荐使用WeakReferenceMessenger(需安装CommunityToolkit.Mvvm包),它是更现代的消息传递方案,可有效避免MessagingCenter潜在的内存泄漏问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 22:25:20