问题描述
使用 Xamarin 共享项目.
Using Xamarin Shared Project.
我尝试在我的共享项目中包含 Xlabs 示例中的地理定位功能,但在调用依赖项服务时遇到了问题.
I tryed to include in my share project the Geolocation feature from Xlabs sample but i'm having problems when it comes to call the dependencyService.
我有一个内容页面,在那里我有我的按钮,它有一个这样的命令:Command = new Command(async () => await GetPosition(), () => Geolocator != null)
I have a content page and in there i have my button that has a command like this: Command = new Command(async () => await GetPosition(), () => Geolocator != null)
命令导致:
private IGeolocator Geolocator
{
get
{
if (_geolocator == null)
{
_geolocator = DependencyService.Get<IGeolocator>();
_geolocator.PositionError += OnListeningError;
_geolocator.PositionChanged += OnPositionChanged;
}
return _geolocator;
}
}
以及何时应该调用 _geolocator = DependencyService.Get<IGeolocator>();
什么也没有发生,_geolocator 保持为空.
and when it should call the _geolocator = DependencyService.Get<IGeolocator>();
nothing happens and _geolocator remains null.
我拥有来自 Xlabs 的所有引用,并且接口 IGeolocator 在我的项目中,为什么不调用 DependencyService??
I have all the references from Xlabs and the interface IGeolocator is in my project so why isn't the DependencyService being called??
推荐答案
XLabs.Platform 服务不再(自更新到 2.0)自动注册到 Xamarin.Forms.DependencyService.这是由于删除了 Xamarin.Forms 对 XLabs.Platform 的依赖.您可以手动注册 Geolocator(从每个平台特定的项目):
XLabs.Platform services are no longer (since update to 2.0) automatically registered with Xamarin.Forms.DependencyService. This is due to removal of Xamarin.Forms dependency on XLabs.Platform. You can either register the Geolocator manually (from each platform specific project):
DependencyService.Register<Geolocator> ();
更好的选择是使用 XLabs.IoC 提供的 IoC 容器抽象(作为依赖项自动包含):https://github.com/XLabs/Xamarin-Forms-Labs/wiki/IOC
Better option would be to use the IoC container abstraction provided by XLabs.IoC (included automatically as dependency): https://github.com/XLabs/Xamarin-Forms-Labs/wiki/IOC
有关 XLabs.IoC 的更多信息:http://www.codenutz.com/autofac-ninject-tinyioc-unity-with-xamarin-forms-labs-xlabs/
More on XLabs.IoC: http://www.codenutz.com/autofac-ninject-tinyioc-unity-with-xamarin-forms-labs-xlabs/
这篇关于Xamarin,使用来自 Xlabs 示例的地理定位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!