(UWP) 索引列表在访问 ComboBox 时导致 System.ArgumentOutOfRangeException

问题描述 投票:0回答:1

我有一个问题,索引列表会破坏看似与之无关的代码。对 List 做任何事情都会导致异常,但如果我只是删除

activePeople[]
ComboBox 代码就可以工作。在这两种情况下,我都查看了所有列表并确保所有列表中都有值,所以我不明白怎么会有 OutOfRange 异常。

下面的代码只是取自实际代码的一部分,并没有遵循相同的结构,但是

peopleBox
和'activePeople'都会在任何代码运行之前填充,并且
SelectionChanged()
总是在
RemovePersonClick()
之前运行。注意 peopleBox 绑定到 ComboBox

class Person 
{
    public string ID;
    public string Name;
}

ObservableCollection<string> peopleBox = new ObservableCollection<string> { "All" }; // More items are added before any of this code runs
List<Person> activePeople = new List<Person>(); // this also get's populated before any of the other code runs

private void RemovePersonClick(object sender, RoutedEventArgs e) 
{
    int selectedPersonIndex = ComboBox.SelectedIndex;

    if(selectedPersonIndex < 1) return; //Don't do anything if "All" or nothing is selected

    activePeople.RemoveAt(selectedPersonIndex - 1); // -1 because it doesn't contain "All" at the start

    //Both of these throw System.ArgumentOutOfRangeException
    //Even though I have verified that the indexes exist
    ComboBox.SelectedIndex = 0; // 0 index always exists as "All" is never removed, i've even tried -1 which should be nothing, but it throws the error
    peopleBox.RemoveAt(selectedPersonIndex);
}

// This code is always run before the RemovePersonClick method
private void SelectionChanged(object sender, SelectionChangedEventArgs e) 
{
    //This causes the issue. If i index activePeople in any way, an error will be thrown in the RemovePersonClick method.
    //Removing this line stops the error. I can't find any link between the two, and I have verified that nothing is out of range.
    string ID = activePeople[0].ID;
}

我已经尝试删除确实解决了问题的

activePeople[0]
,但我需要从
activePeople
中获取值。我检查过 ComboBox 和 peopleBox 中确实存在值,但我仍然收到错误消息。

c# .net uwp combobox outofrangeexception
1个回答
0
投票

// -1 因为它的开头不包含“全部”

所以如果你删除所有项目,

activePeople
将变为空,在这种情况下访问
activePeople[0]
是无效的,你应该这样处理这个异常。

string ID = activePeople.Count > 0 ? activePeople[0].ID : "All";
© www.soinside.com 2019 - 2024. All rights reserved.