Reputation: 13898
I am going to be developing a large project which will include a large number of ComboBoxes.
Most of these combo boxes will be bound to a database field which is a related to another daataset/table.
For instance.
I have the following 2 tables:
Company {CompanyID, CompanyName, MainContact}
Contacts {ContactID, ContactName}
And when the user clicks to edit a company, A TextBox will be there to edit a company name, but also a ComboBox will be there.
The way I am currently doing it is binding the ComboBox to the Contacts dataset, and manually updating the Company MainContact field in code behind.
Is there anyway for me to bind the selected item to the Company MainContact field in XAML and the items to the ContactName and eliminate the code behind?
Reason for this is when you start making 100's combo boxes all over the application it gets long winded each time creating code behind to do the update.
Would this be at all possible?
Upvotes: 1
Views: 1808
Reputation: 1773
First of all, I highly recommend using the MVVM design pattern for your application. The databinding and commanding in a MVVM app alone will save you an enormous amount of time.
But anyway, I'll get off my soapbox and tell you how to properly bind your combobox:
<ComboBox ItemsSource="{Binding Contacts}" DisplayMemberPath="ContactName"
SelectedValue="{Binding Path=Company.MainContact,
UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="ContactName"/>
As you can see, the ItemsSource is bound to your Contacts dataset, but the when the user selects an item from the list, it will update the Company.MainContact field with the selected contact.
Upvotes: 2