我创建了一个要求输入用户名并返回该用户统计信息的应用程序。当计数器大于1时,它将着重于选择器并要求选择其中一个选项。之后,将调用SelectedIndexChanged(Platformselect_SelectedIndexChanged)方法并获取统计信息。问题在于,如果用户输入用户名,则该用户名将首次生效。当用户返回并重新输入用户名时,它不会聚焦(它不会显示选择器),并以platformselect.SelectedIndex为-1自动调用SelectedIndexChanged方法,导致程序崩溃。你能帮我吗?
我试图将重点放在主线程上,我已经在iOS和Android上对其进行了测试,并且出现了相同的问题。
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
platformselect.HeightRequest = 0;
this.search.Clicked += Button_Clicked;
}
public async void searchStats(string usernameText)
{
search.IsEnabled = false;
activityIndicator.IsRunning = true;
var id = await GetDataLogic.GetID(usernameText);
publicid = id;
activityIndicator.IsRunning = false;
if (id.uid == "error")
{
await DisplayAlert("Error", "Could not find username: " + usernameText, "OK");
search.IsEnabled = true;
return;
}
else if (id.uid == "errornointernet")
{
await DisplayAlert("Error", "Could not connect to the Internet. Please check your connection and try again.", "OK");
search.IsEnabled = true;
return;
}
else
{
if(id.platforms.Count > 1)
{
platformselect.ItemsSource = publicid.platforms.ToList();
//we have to show alert to choose platform and then call get user stats.
**Device.BeginInvokeOnMainThread(() =>
{
if (platformselect.IsFocused)
platformselect.Unfocus();
platformselect.Focus();
});**
}
else
{
//we call it without asking because there is only one platform.
var userstats = await GetDataLogic.GetStats(id, 0);
await Navigation.PushAsync(new Stats(userstats, favorites));
}
}
}
private async void Platformselect_SelectedIndexChanged(object sender, EventArgs e)
{
//the second time it doesnt show the picker and it automatically enters -1... it returns null exception. Has to be investigated.
var userstats = await GetDataLogic.GetStats(publicid, platformselect.SelectedIndex);
await Navigation.PushAsync(new Stats(userstats, favorites));
}
}
我希望它始终专注于选择器并等待用户的响应,而不是自动将-1作为selectedindex调用SelectedIndexChanged
答案 0 :(得分:0)
我建议以这种方式更改事件处理程序
private async void Platformselect_SelectedIndexChanged(object sender, EventArgs e)
{
//Check for unselection event
if(platformselect.SelectedIndex == -1) return;
var userstats = await GetDataLogic.GetStats(publicid, platformselect.SelectedIndex);
await Navigation.PushAsync(new Stats(userstats, favorites));
}