簡體   English   中英

Xamarin,使用Xlabs示例中的Geolocation

[英]Xamarin, using Geolocation from Xlabs sample

使用Xamarin共享項目。

我試圖在我的共享項目中包括Xlabs示例中的Geolocation功能,但是在調用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?

XLabs.Platform服務不再(自更新至2.0)不再自動向Xamarin.Forms.DependencyService注冊。 這是由於刪除了XLabs.Platform上的Xamarin.Forms依賴關系。 您可以手動注冊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/

Command Constructor的第二個參數是一個函數,該函數告訴命令是否可以執行,在您的情況下,您正在“告訴”僅當Geolocator is != null時才執行命令,但是您正在命令中對其進行初始化,永遠不會執行,因為Geolocator為null。

您應該在調用命令之前初始化Geolocator或刪除Geolocator is != null條件才能執行命令。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM