2017-09-03 45 views
0

我正在使用MvvmCross框架,我想从Core项目中调用Android项目中定义的方法。我试图This解决办法,但我收到以下错误调用PCL项目中UI项目中定义的方法

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

因为我没有使用Xamarin表格,所以我知道这是行不通的。有没有任何解决方法或任何其他方式来实现这一目标?

回答

0

最后找到答案。下面是步骤

- 获取NuGet包 “Xamarin.Forms.Labs” 在你的Android(UI)的项目,显然现在是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和链接提到的问题,如果你想做更多的研究。希望这可以帮助别人。

0

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

+0

谢谢** lowleetak **为您的答案,但如果我使用依赖注入然后我进入另一个问题,即如何引用PCL的App.cs中的UI类? 因为这会导致循环依赖和VS不会允许它。如果你能提供一个小例子作为参考,那将是非常好的。 –

+0

您需要更具体地了解您尝试实现的目标,以便我们提供更多详细的答案 – lowleetak

相关问题