【问题标题】:Xamarin, using Geolocation from Xlabs sampleXamarin,使用来自 Xlabs 示例的 Geolocation
【发布时间】:2015-07-15 15:51:27
【问题描述】:

使用 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&lt;IGeolocator&gt;(); 时什么也没有发生,_geolocator 保持为空。

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

【问题讨论】:

    标签: c# android xamarin xamarin.forms xlabs


    【解决方案1】:

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

     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/

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-04
        相关资源
        最近更新 更多