[英]Using VS2012 GUI to bind ListBox to List<T>
I feel like this is such a basic question, but I've spent 2 days trying to get it working with no success. 我觉得这是一个基本的问题,但是我花了2天的时间才能使其成功。 Thank you for your time. 感谢您的时间。
Form
) MyForm( Form
)
ListBox
myListBox- ListBox
string
firstName- string
string
lastName- string
List<MyDataElement>
myDataList- List<MyDataElement>
Using the GUI, how can I bind myListBox
to myDataList
? 使用GUI,我怎么可以绑定myListBox
到myDataList
? More specifically, how do I go about instantiating MyDataManager
so that myListBox
gets populated with the list's values? 更具体地讲,我怎么去实例MyDataManager
使myListBox
获取与该列表的值填充?
I can create DataSources without trouble, but I cannot get the ListBox to show the contents of the underlying list. 我可以毫不费力地创建DataSources,但无法获取ListBox来显示基础列表的内容。 I have tried: 我努力了:
MyDataManager
object 将ListBox绑定到独立的MyDataManager
对象 MyForm
of type MyDataManager
and binding the ListBox to that member 在MyDataManager
类型的MyForm
中创建一个成员并将ListBox绑定到该成员 I couldn't get either to work. 我都不能上班。 I've also tried changing the DisplayMember property to no avail. 我也尝试将DisplayMember属性更改为无效。
Incidentally, I can get it to work properly by manually setting the DataSource (eg, myListBox.DataSource = myDM.myDataList
) in the main method of MyForm
, but for future reference and my own edification I would love to learn how to do this through the GUI (if it's even possible). 顺便说一句,我可以通过在MyForm
的主要方法中手动设置DataSource(例如, myListBox.DataSource = myDM.myDataList
)来使其正常工作,但是为了将来参考和我自己的观点,我很乐意学习如何通过GUI(如果可能的话)。
public class MyDataElement
{
public string firstName { get; set; }
public string lastName { get; set; }
public override string ToString()
{
return firstName + " " + lastName;
}
}
public class MyDataManager
{
public List<MyDataElement> myDataList { get; set; }
// Constructor.
public MyDataManager()
{
myDataList = new List<MyDataElement>();
// Populate list for testing purposes.
myDataList.Add(new MyDataElement { firstName = "John", lastName = "Smith" });
myDataList.Add(new MyDataElement { firstName = "Jane", lastName = "Doe" });
}
}
In the main method of MyForm
: 在MyForm
的主要方法中:
// ...
myDM = new myDataManager();
InitializeComponents();
// ...
I have also tried reversing this order. 我也尝试过反转此顺序。
You need to bind your View's DataContext with MyDataManager using Resources(In your case MyDataManager is considered as the ViewModel), see these anwsers . 您需要使用资源将视图的DataContext与MyDataManager绑定(在您的情况下,将MyDataManager视为ViewModel),请参见这些anwsers 。 The VS GUI will be able to find your MyDataManager class members then. VS GUI将能够找到您的MyDataManager类成员。 Hope it helps 希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.