从 PCL 项目调用 UI 项目中定义的方法

Invoking a method defined in UI project from PCL Project

我正在使用 MvvmCross 框架,我想从 Core 项目调用 Android 项目中定义的方法。我尝试了 This 解决方案,但出现以下错误

Unhandled Exception: System.InvalidOperationException: You MUST call Xamarin.Forms.Init(); prior to using it. occurred

因为我没有使用 Xamarin Forms,所以我知道这行不通。是否有任何解决方法或任何其他方法来完成此操作?

DependencyService 是 Xamarin Forms 中的一项功能。如果您正在使用 MvvmCross,您应该从 MvvmCross 查看依赖注入。 https://www.mvvmcross.com/documentation/fundamentals/dependency-injection

终于找到答案了。以下是步骤

I - 在你的 android (UI) 项目中获取 nuget 包 "Xamarin.Forms.Labs",显然现在是 Scorchio.NinjaCoder.Xamarin.Forms.Labs

II - 在SetUp.cs中使用如下代码如下图

using Android.Content;
using MvvmCross.Core.ViewModels;
using MvvmCross.Droid.Platform;
using Xamarin.Forms.Labs.Services;

namespace SomeProject.UI.Droid
{
    public class Setup : MvxAndroidSetup
    {

        public Setup(Context applicationContext) : base(applicationContext)
        {
            var resolverContainer = new SimpleContainer();
            resolverContainer.Register<IViewMethodCallService>(t => new ViewMethodCallService());
            Resolver.SetResolver(resolverContainer.GetResolver());
        }

        protected override IMvxApplication CreateApp()
        {
            return new App();
        }
    }
}

其中“IViewMethodCallService”是接口,具有方法的签名,例如TestMethod(),在您的 PCL 项目中,“ViewMethodCallService.cs”是 [=53= 中该接口的实现] 或 Android 个项目。

III - 现在创建接口“IViewMethodCallService”的对象,如下所示

IViewMethodCallService callMethod= Resolver.Resolve<IViewMethodCallService>();
callMethod.TestMethod();

ViewMethodCallService.cs”看起来像这样

using Android.Util;

[assembly: Xamarin.Forms.Dependency(typeof(ViewMethodCallService))]
namespace SomeProject.UI.Droid
{    
    public class ViewMethodCallService : Java.Lang.Object, IViewMethodCallService
    {
        public ViewMethodCallService()
        {

        }

        public void TestMethod()
        {
            Log.Info("Hurrayyyyyyyyyyyyyyyyyyyyyyyyyy", "And I am calling this service");
        }
    }
}

我从 this question 和问题中提到的 link 那里得到了这个答案,如果你想做更多的研究。希望这对某人有所帮助。