Wp7 ListBox ItemSource ObservableCollection IndexOUtofRange和Items不会更新

时间:2011-06-28 08:09:03

标签: c# windows-phone-7 listbox observablecollection itemsource

我有以下问题:我正在创建一个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));

    }

}

人物集合中填充了Person对象。它们是在以下函数中创建的... 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事件被触发时,我尝试使用以下代码重建整个列表(所以我再次调用上面的函数):

            string id = people[listValues.SelectedIndex].Id;
        MessageBox.Show(id);
        CreateHierachy(id);

CreateHierachy只查询WebService,然后进入上面的方法。问题是,只要我在ListBox中选择一个值,我就会收到以下错误:

ArgumentOutOfRangeException {"\r\nParameter name: index"}

错误是由行listValues.SelectedIndex引起的。 我完全不知道为什么会这样。我所知道的是MessageBox向我显示了正确的SelectedIndex值。我也知道当我删除行people.Clear()时,错误消失但ListBox没有得到更新。

可能存在问题的任何想法?

感谢!!!

再见 WorldSignia

1 个答案:

答案 0 :(得分:0)

您应在此处查看SelectedIndex是> = 0:

if (listValues.SelectedIndex >= 0)
     string id = people[listValues.SelectedIndex].Id;
相关问题