我安装了最新的 Xamarin Alpha,但无法使 UWP 和 DependencyService 正常工作。
在 UWP 项目中我有:
Forms.Init(e);
// For release version, doc said debug will do this itself
DependencyService.Register<SpecialInterface>();
IInterface1 iinterface1 = DependencyService.Get<IInterface1>();
这确实找到了接口(interface)指针。
在 PCL 中我有:
IInterface1 iinterface1 = DependencyService.Get<IInterface1>();
在 PCL 中包含的 View 模型中(单击按钮后),它无法返回 null
Get<IInterface1>()
的值在 UWP 和 Android 上调用。
以下是 UWP 项目中包含的实现:
using PrismUnityApp2.UWP;
using SharedProject1;
using Xamarin.Forms;
[assembly: Dependency(typeof(SpecialInterface))]
namespace PrismUnityApp2.UWP
{
public class SpecialInterface : IInterface1
{
public SpecialInterface() { }
public int TestMethod(int i)
{
return i;
}
}
}
最后,接口(interface)在共享项目中定义如下:
namespace SharedProject1
{
internal interface IInterface1
{
int TestMethod(int i);
}
}
我的示例“UsingDependencyService”在 Android 中工作,WinPhone 失败,因为 Android 上的 HyperV 已关闭。
我错过了什么?
感谢您的帮助。
使用以下软件包/版本:
- Prism.Unity.Forms 6.2.0.pre4
- Prism.Forms 6.1.0.pre4
- Xamarin.Forms 2.2.0.45
- Unity 4.0.1
Windows 10 UWP
public void OnNavigatedTo(NavigationParameters parameters) { if (parameters.ContainsKey("title")) Title = (string) parameters["title"] + " and Prism"; IInterface1 iinterface1 = DependencyService.Get<IInterface1>(); if (iinterface1 != null) { int value = iinterface1.TestMethod(1); Title += " ::: " + value; } }
最佳答案
DependencyService.Get<IInterface1>()
调用在 PCL 中返回 null,因为它正在寻找 IInterface1
的不同版本它实际上被定义了多次。
因为IInterface1
位于由 PCL 项目和 UWP & Android 项目引用的共享项目中,它与在 PCL 和应用程序项目中分别创建具有相同名称和签名的界面基本相同。然而父程序集是不同的。
如果你要搬家IInterface1
到您现有的 PCL 或由现有 PCL 和您的应用程序项目引用的单独 PCL,DependencyService
应该能够找到您的平台特定实现,SpecialInterface
,正如预期的那样。
关于c# - Xamarin.Forms DependencyService Get() 方法在 PCL 中返回 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37735586/