使用Xamarin共享项目。
我尝试在我的共享项目中包括XLABS样本中的地理位置功能,但在致电disporencyService时遇到问题。
我有一个内容页面,在那里,我的按钮具有这样的命令: 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保持null。
我有来自XLABS的所有参考,并且Interface Igeolocator在我的项目中
xlabs.platform服务不再(因为更新为2.0)自动在xamarin.forms.deppercyencyservice上注册。这是由于去除Xamarin.Forms对Xlabs.s.platform的依赖。您可以手动注册地理定位器(从每个平台特定项目):
DependencyService.Register<Geolocator> ();
更好的选择是使用Xlabs.ioc提供的IOC容器抽象(自动包含在依赖项):https://github.com/xlabs/xamarin-forms-labs/wiki/wiki/ioc/ioc
更多有关Xlabs.ioc的信息:http://www.codenutz.com/autofac-ninject-tinyioc-unity-with-xamarin-forms-labs-labs-xlabs/
命令构造器的第二个参数是一个函数,可以告诉命令是否可以执行,在您的情况下,您是在"告诉" Geolocator is != null
时仅执行命令,但是您在您的命令中初始化它,因为地理器为null。
您应该在调用命令或删除Geolocator is != null
条件之前初始化Geolocator。