0

我对 WPF 中的数据绑定有一个困惑的问题。XAML 中有一个与 ItemSource 链接的列表框,但是当它运行时,它会显示类名列表。所以我已经申请了 DisplayMemberPath,但它没有帮助。而且我想知道如何从泛型类访问类内部。谢谢。

结果

puzzled.Member
puzzled.Member
puzzled.Member
puzzled.Member

<DockPanel>        
    <ListBox Name="lbxMbrList" DockPanel.Dock="Left" Width="200" Padding="10"></ListBox>
    <ContentControl />
</DockPanel>

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 = members.MemberDetails;   //<<it won't helpful

    //var i = members.member.Name;                          //<<how can I access inside class?
    //if (i == "superman")
    //{
    //    MessageBox.Show("superman");
    //}

}

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, Address); }
    }

}

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 Member member { get; set; }     //<< it think I has misunderstood it
    public string MemberDetails
    {
        get
        { return string.Format("{0} - {1}", member.Name, member.Phone, member.Address); }
    }

}  
4

2 回答 2

1

您正在将 MemberDetails 属性的输出分配给 DisplayMemberPath。相反,您需要将属性名称指定为字符串。

lbxMbrList.DisplayMemberPath = "MemberDetails";

对于它的价值,如果您在 ListBox 中使用 ItemTemplate,这将更容易使用。

[编辑]

此外,正如@Blam 在他的回答中提到的那样,您的 MemberDetails 属性是在错误的类中定义的,它需要在 Member 类中。

于 2014-12-12T17:53:49.783 回答
0
lbxMbrList.DisplayMemberPath = "lbxMember";

或者

lbxMbrList.DisplayMemberPath = "MemberDetails";

并且 MemberDetails 需要是 Member 的属性(不是 MemberList)

于 2014-12-12T17:52:25.107 回答