【问题标题】:Invoking a method defined in UI project from PCL Project从 PCL 项目调用 UI 项目中定义的方法
【发布时间】:2017-10-10 22:42:13
【问题描述】:

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

未处理的异常: System.InvalidOperationException:您必须调用 Xamarin.Forms.Init();在使用它之前。发生了

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

【问题讨论】:

    标签: c# android xamarin.android mvvmcross


    【解决方案1】:

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

    【讨论】:

    • 感谢 lowleetak 的回答,但是如果我使用依赖注入,那么我会遇到另一个问题,即如何在 PCL 的 App.cs 中引用 UI 类?因为这会导致循环依赖,而 VS 不允许这样做。如果您能提供一个小例子作为参考,那就太好了。
    • 您需要更具体地说明您要达到的目标,以便我们提供更详细的答案
    【解决方案2】:

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

    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”是 UI 或 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 得到了这个答案,如果您想进行更多研究,请参考相关链接。希望这对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 1970-01-01
      • 2017-08-25
      • 2014-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多