C# 如何在没有<;按钮/>;?
我有一个带有按钮的简单表单,按钮获取当前地理位置坐标并显示在两个标签上 守则:C# 如何在没有<;按钮/>;?,c#,ios,visual-studio,xamarin,C#,Ios,Visual Studio,Xamarin,我有一个带有按钮的简单表单,按钮获取当前地理位置坐标并显示在两个标签上 守则: public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); } private async void Button_Clicked(System.Object sender, System.EventArgs e) { t
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}");
}
}
}
所以按钮上的方法是异步的。。我想从InitializeComponent()下的按钮中移动代码强>
我想知道应用程序何时开始在标签上显示地理位置坐标,而无需单击按钮
我尝试从InitializeComponent()下的按钮中移动代码但我看到了以下错误消息:
所以。。如何从构造函数中单击的按钮中移动代码
我尝试删除构造函数中的wait,如下所示:
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将您的代码放入出现的
事件中
protected async override void OnAppearing()
{
base.OnAppearing();
// your code goes here
}
将代码放入出现的事件中
protected async override void OnAppearing()
{
base.OnAppearing();
// your code goes here
}
您可以创建另一个异步方法,如private async string GetUserLocationAsync()
,并将代码放在其中。然后在InitializeComponent()
之后调用该方法,您可以创建另一个异步方法,如私有异步字符串GetUserLocationAsync()
,并将代码放入其中。然后在InitializeComponent()
location=Geolocation.GetLocationAsync(新的GeolocationRequest(){DesiredAccuracy=GeolocationAccuracy.Medium,Timeout=TimeSpan.FromSeconds(30)})之后调用该方法;当我删除wait时,我在这一行有问题:else{LabelLocation.Text=$“{location.Latitude}{location.Longitude}”;}错误是:CS1061but.Result;在endlocation=Geolocation.GetLocationAsync(new GeolocationRequest(){DesiredAccuracy=GeolocationAccuracy.Medium,Timeout=TimeSpan.FromSeconds(30)})处);当我删除wait时,我在这一行有问题:else{LabelLocation.Text=$“{location.Latitude}{location.Longitude}”;}错误是:CS1061but.Result;在内联,请使用评论功能询问其他问题。请勿编辑回答,请使用评论功能询问其他问题。不要编辑答案