问题描述
我有一个带有按钮的简单表单,它可以获取当前的地理位置坐标并显示在两个标签上。
代码:
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(); 下的按钮,但是我看到以下错误消息:
所以..如何从构造函数中的Button_Clicked中移动代码?
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
解决方法
将您的代码放入OnAppearing
事件
protected async override void OnAppearing()
{
base.OnAppearing();
// your code goes here
}
,
您可以创建另一个private async string GetUserLocationAsync()
之类的异步方法,并将代码放入其中。然后在InitializeComponent()