如何在没有<Button />的情况下在Xamarin中显示当前地理位置坐标?

问题描述

我有一个带有按钮的简单表单,它可以获取当前的地理位置坐标并显示在两个标签上。

代码

public partial class MainPage : ContentPage
{   
    public MainPage()
    {
        InitializeComponent();
    }

    private async void Button_Clicked(System.Object sender,System.EventArgs e)
    {
        try
        {
            var location = await Geolocation.GetLastKNownLocationAsync();

            if (location == null)
            {
                location = await Geolocation.GetLocationAsync(new GeolocationRequest()
                {
                    DesiredAccuracy = GeolocationAccuracy.Medium,Timeout = TimeSpan.FromSeconds(30)
                });
            }
            if (location == null)
            {
                LabelLocation.Text = "No GPS";
            }
            else
            {
                LabelLocation.Text = $"{location.Latitude} {location.Longitude}";
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine($"Something is wrong : {ex.Message}");
        }

    }
}

所以Button上的方法是异步的。我想从 InitializeComponent();

下的按钮移动代码

我希望当应用程序开始在标签显示地理位置坐标时,无需单击按钮。

我尝试将代码移到 InitializeComponent(); 下的按钮,但是我看到以下错误消息:

Error

所以..如何从构造函数中的Button_Clicked中移动代码

我尝试像这样在构造函数删除await:

public MainPage()
    {
        InitializeComponent();

        try
        {
            var location =  Geolocation.GetLastKNownLocationAsync();

            if (location == null)
            {
                location =  Geolocation.GetLocationAsync(new GeolocationRequest()
                {
                    DesiredAccuracy = GeolocationAccuracy.Medium,Timeout = TimeSpan.FromSeconds(30)
                });
            }
            if (location == null)
            {
                LabelLocation.Text = "No GPS";
            }
            else
            {
                LabelLocation.Text = $"{location.Latitude} {location.Longitude}";
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine($"Something is wrong : {ex.Message}");
        }

    }

但是我收到以下错误消息:CS1061

after remove await

解决方法

将您的代码放入OnAppearing事件

protected async override void OnAppearing()
{
    base.OnAppearing();

    // your code goes here
}
,

您可以创建另一个private async string GetUserLocationAsync()之类的异步方法,并将代码放入其中。然后在InitializeComponent()

之后立即调用该方法