[英]Wp7 ListBox ItemSource ObservableCollection IndexOUtofRange and Items are not updated
我有以下问题:我正在创建一个 Windows Phone 7 应用程序,并且我正在使用一个绑定到 ObservableCollection 人的 ListBox。 你在下面看到这个的实现:
public class Person
{
private string _id { get; set; }
private string _name { get; set; }
public Person(string Id, string Name, string Title)
{
_id = Id;
_name = Name;
}
public string Id
{
get { return _id; }
set
{
_id = value;
FirePropertyChangedEvent("Id");
}
}
public string Name
{
get { return _name; }
set
{
_name = value;
FirePropertyChangedEvent("Name");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void FirePropertyChangedEvent(string propertyName)
{
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
people 集合中充满了 Person 对象。 它们是在以下 function 中创建的... listValues 是我的 ListBox。
void svc_GetHierachyCompleted(object sender, HCMobileSvc.GetHierachyCompletedEventArgs e)
{
var data = e.Result.ToArray();
listValues.ItemsSource = null;
people.Clear();
int i = 0;
foreach(var item in data)
{
if (i == 0)
{
// Manager
mgrField1.Text = item[1].ToString();
mgrField2.Text = item[2].ToString();
i++;
}
else
{
// Untergebenen hinzufügen
people.Add(new Person(item[0].ToString(), item[1].ToString(), item[2].ToString()));
}
}
// Update List
listValues.ItemsSource = people;
}
现在我有一个 DataTemplate,其中有两个文本块绑定到属性 Id 和 Name。 当 SelectionChanged 事件被触发时,我尝试使用以下代码重建整个列表(因此我再次调用上面的 function):
string id = people[listValues.SelectedIndex].Id;
MessageBox.Show(id);
CreateHierachy(id);
CreateHierachy 只查询一个 WebService,然后进入上面的方法。 问题是,只要我 select 在 ListBox 中有一个值,我就会收到以下错误:
ArgumentOutOfRangeException {"\r\nParameter name: index"}
该错误是由行 listValues.SelectedIndex 引起的。 我完全不知道为什么会这样。 我所知道的是 MessageBox 向我显示了正确的 SelectedIndex 值。 我还知道,当我删除 people.Clear() 行时,错误消失但 ListBox 没有得到更新。
问题可能出在哪里?
谢谢!!!
再见,世嘉
您应该在此处检查SelectedIndex
是否 >= 0:
if (listValues.SelectedIndex >= 0)
string id = people[listValues.SelectedIndex].Id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.