我有两个选择器。第二个选择器依赖于第一个选择器。两个选择器都从服务绑定(bind)。我正在使用字典对象将数据绑定(bind)到选择器。 我没有使用 MVVM 模式。
- 第一个服务调用,其中绑定(bind)了第一个选择器的字典对象。
- 然后从该字典对象中填充第一个选择器。那时第二个选择器是空的。
- 在第一个选择器调用服务的 selectedIndexChange 事件上绑定(bind)第二个选择器的字典对象。
- 现在将字典对象中的值填充到第二个选择器。 (如果选择器已经有数据,则放入 Picker.Items.clear())
- 现在,如果我从第二个选择器中选择一些值并更改第一个选择器的值,那么它会在 Picker.Items.clear() 处给我错误
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
全局声明:
Dictionary<string, string> DicObjActivityType;
Dictionary<string, string> DicObjSelfActivity;
First Picker selectedIndexChange 事件
private async void PckrActivityType_SelectedIndexChanged(object sender, EventArgs e)
{
if (sender as Picker == null)
return;
else
{
var objActivityType = sender as Picker;
var Key = DicObjActivityType.FirstOrDefault(x => x.Value == objActivityType.Items[objActivityType.SelectedIndex]).Key;
PickedActivityType = Key;
if (Key != "0")
{
PckrSelfActivity.IsEnabled = true;
await CallGetWebService_SelfActivity(Key);
if (PckrSelfActivity.IsEnabled == true)
{
PckrSelfActivity.Items.Clear();
foreach (string items in DicObjSelfActivity.Values)
{
PckrSelfActivity.Items.Add(items);
}
}
}
else
{
PckrSelfActivity.IsEnabled = false;
}
}
}
调用秒选服务
private async Task CallGetWebService_SelfActivity(string strkey)
{
try
{
var response = await GetResponseFromWebService.GetResponse<ServiceClasses.RootObject_LstListComboData>(ServiceURL.GetSelfActivity + "ActivityTypeCd=" + strkey);
if (response.Flag == true)
{
DicObjSelfActivity = new Dictionary<string, string>();
DicObjSelfActivity.Add("0", "--Select--");
if (response.lstListComboData != null)
{
foreach (ServiceClasses.LstListComboData Items in response.lstListComboData)
{
DicObjSelfActivity.Add(Items.Value, Items.Text);
}
}
}
else
{
PckrSelfActivity.IsEnabled = false;
}
}
catch (Exception e)
{
await DisplayAlert(AppResources.LError, AppResources.LConnectionError, "OK");
}
}
我引用以下链接来解决这个问题
https://forums.xamarin.com/discussion/55922/picker-clear-system-argumentoutofrangeexception
但没有找到解决方案。
如果选择了任何值,我们无法清除选择器?
我不想使用 BindablePicker 自定义控件。
最佳答案
我不确定您所说的“清除选择器”是否是指重置它,使其不显示任何已选择的项目。但如果这就是您想要的,那么您可以执行以下操作:
设置
SelectedIndex = -1
。这将重置选择器,以便不选择任何项目。设置
SelectedIndex = -1
后,将调用selectedIndexChange
事件处理程序,这会导致
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
确实是的,SelectedIndex
是-1
,所以它提示索引必须是非负的。
- 要避免 ArgumentOutOfRangeException,请添加包含
SelectedIndexChange
事件处理程序的if
语句,以便处理程序仅执行if (SelectedIndexChange != -1)
.
总而言之,这样做:
YourPicker.SelectedIndex = -1;
YourPicker.SelectedIndexChanged += (sender, e) =>
{
if (YourPicker.SelectedIndex != -1)
{
//Do your stuff
}
}
关于c# - 如果以 xamarin 形式选择它,如何清除选择器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40676143/