binding itemsource of two way in codebehind?

70 views Asked by At

there is a listbox was binding with itemsource. I want to change the data of collection after then. the click button of adding data doesn't make change the listbox.

then I add the update after the itemsource, but it makes PresentatonFramework.pdb not loaded, InvalidOperationException was unhandled. what I have little bit understood, it is one way binding. Would you give me some help?

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); }
    }
}
1

There are 1 answers

2
paparazzo On BEST ANSWER

You use ObservableCollection under to covers but you expose it as IEnumerable

IEnuerable does not deal with notify the UI of inserts and deletes.

Why not just use ObservableCollection and skip this MemberList?