Xamarin,使用来自 Xlabs 示例的地理定位

Xamarin, using Geolocation from Xlabs sample

使用 Xamarin 共享项目。

我尝试在我的共享项目中包含来自 Xlabs 示例的地理定位功能,但在调用 dependencyService 时遇到问题。

我有一个内容页面,里面有我的按钮,上面有这样的命令: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 仍然为空。

我有来自 Xlabs 的所有引用,并且 IGeolocator 接口在我的项目中,那么为什么没有调用 DependencyService?

Command Constructor的第二个参数是一个判断命令是否可以执行的函数,在你的情况下你是"telling"只在Geolocator is != null时执行命令,但是你是在您的命令中初始化它,该命令永远不会执行,因为 Geolocator 为空。

您应该在调用命令之前初始化 Geolocator 或删除 Geolocator is != null 条件以执行命令。

XLabs.Platform 服务不再(自更新到 2.0)自动注册到 Xamarin.Forms.DependencyService。这是由于移除了 Xamarin.Forms 对 XLabs.Platform 的依赖。您可以手动注册地理定位器(从每个平台特定项目):

 DependencyService.Register<Geolocator> ();

更好的选择是使用 XLabs.IoC 提供的 IoC 容器抽象(作为依赖项自动包含):https://github.com/XLabs/Xamarin-Forms-Labs/wiki/IOC

关于 XLabs.IoC 的更多信息:http://www.codenutz.com/autofac-ninject-tinyioc-unity-with-xamarin-forms-labs-xlabs/