我在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); }
}
}
答案 0 :(得分:1)
您正在将MemberDetails属性的输出分配给DisplayMemberPath。相反,您需要将属性的名称指定为字符串。
lbxMbrList.DisplayMemberPath = "MemberDetails";
如果你在ListBox中使用ItemTemplate,那么它的价值就更容易了。
[编辑]
另外,正如@Blam在他的回答中提到的,你的MemberDetails属性是在错误的类中定义的,它需要在Member类中。
答案 1 :(得分:0)
lbxMbrList.DisplayMemberPath = "lbxMember";
或
lbxMbrList.DisplayMemberPath = "MemberDetails";
并且MemberDetails需要是Member(不是MemberList)的属性