0

有一个列表框与 itemsource 绑定。之后我想更改收集的数据。添加数据的单击按钮不会更改列表框。

然后我在 itemsource 之后添加更新,但它使 PresentatonFramework.pdb 未加载,InvalidOperationException 未处理。我有点了解,这是一种绑定方式。你能给我一些帮助吗?

private MemberList members = new MemberList();

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    members.Add(new Member("superman", "123-1234567", "address1"));
    members.Add(new Member("batman", "111-111111", "address2"));
    members.Add(new Member("goodman", "222-222222", "address3"));
    members.Add(new Member("badman", "333-333333", "address4"));            

    lbxMbrList.ItemsSource = members;
    lbxMbrList.DisplayMemberPath = "lbxMember";

    //members.Add(new Member("puzzedman", "000-0000000", "address0")); //<<it makes a strange error message.
    }

    //I want a button to update the listbox's content
    private void Add_Click(object sender, RoutedEventArgs e)
    {
        members.Add(new Member("puzzedman", "444-4444444", "address5"));
    }

    private void Clear_Click(object sender, RoutedEventArgs e)
    {
        members.Clear();
    }


update:

class MemberList : IEnumerable<Member>
{
    private ObservableCollection<Member> memberList = new ObservableCollection<Member>();

    public Member this[int i]
    {
        get {return memberList[i];}
        set {memberList[i] = value;}
    }

    public void Add(Member member)
    {
        memberList.Add(member);
    }

    public void Remove(Member member)
    {
        memberList.Remove(member);
    }

    public IEnumerator<Member> GetEnumerator()
    {
        return memberList.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }

    public void Clear()
    {
        memberList.Clear();
    }
}

public class Member
{
    private string _name;
    private string _phone;
    private string _address;

    public string Name { get { return _name; } set { _name = value; } }
    public string Phone { get { return _phone; } set { _phone = value; } }
    public string Address { get { return _address; } set { _address = value; } }

    public Member() { }

    public Member(string name, string phone, string address)
    {
        _name = name; _phone = phone; _address = address;
    }

    public string lbxMember
    {
        get { return string.Format("{0} {1}", Name, Phone); }
    }
}
4

1 回答 1

1

您在封面下使用 ObservableCollection,但将其公开为 IEnumerable

IEnuerable 不处理通知 UI 插入和删除。

为什么不直接使用 ObservableCollection 并跳过这个 MemberList?

于 2014-12-13T15:51:17.387 回答