Xamarin, using Geolocation from Xlabs sample

2019-02-20 15:17发布

问题:

Using Xamarin Shared Project.

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.

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)

the Command leads to:

private IGeolocator Geolocator
    {
        get
        {
            if (_geolocator == null)
            {
                _geolocator = DependencyService.Get<IGeolocator>();
                _geolocator.PositionError += OnListeningError;
                _geolocator.PositionChanged += OnPositionChanged;
            }
            return _geolocator;
        }
    }

and when it should call the _geolocator = DependencyService.Get<IGeolocator>(); nothing happens and _geolocator remains null.

I have all the references from Xlabs and the interface IGeolocator is in my project so why isn't the DependencyService being called??

回答1:

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> ();

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

More on XLabs.IoC: http://www.codenutz.com/autofac-ninject-tinyioc-unity-with-xamarin-forms-labs-xlabs/



回答2:

The second parameter of Command Constructor is a function that tell if the command can be executed or not, in your case you are "telling" to only execute the command when Geolocator is != null, but you are initializing it in your command, which is never executed because Geolocator is null.

You should initialize the Geolocator before the command is called or remove the Geolocator is != null condition to execute the command.