WPF Binding ADO.Net Entity Framework to a ComboBox
I am working on a small system for a summer camp in WPF. I have a database that is linked via ADO.Net Entity Framework. It contains two tables; Campers & Bunks. The structure is as follows:
Campers开发者_Python百科
- CustomerID, INT (Key)
- Name, NVARCHAR
- BunkID, INT
Bunks
- BunkID, INT (Key)
- Name, NVARCHAR
There is a foreign key relationship to for the link between Campers.BunkID & Bunks.BunkID
I made a WPF Window that consists of a ListBox of all the customers and a UserControl that displays the details of the customer selected in the ListBox . The UserControl consists of a TextBlock for the CamperID , TextBox for the Name of the camper and ComboBox for the Bunk of the camper.
Now the hard part... I have two questions:
- What is the best method to bind the list of all the Campers to the ListBox ? What is the best way to bind the list of all the Bunks to the ComboBox in the UserControl ?
- I cannot figure out how to bind the ComboBox correctly such that it displays the Bunk for each Camper and can be updated by changing the value.
Currently I am doing both in the code behind in C# but with the strength of WPF, I can't imagine that a simpler and better solution does not exist...
Thanks in advance!
Mike
You should do 3 things:
- Set the ListBox's ItemSource property to the Campers object (I assume this is an IEnumerable of some kind..)
- Set the DisplayMemeberPath property to the actual property you want to display on the ListBox (for instance - "CustomerFirstName"). If you want it to be a bit more complex you can create your own DataTemplate and present whatever you want (more than one property, images, etc)
- Bind the UserControl to the ListBox's selected item:
精彩评论