views:

114

answers:

1

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?

+2  A: 

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.

Brent
Thanks for that. And i am wondering how MVVM would be advantageous to this? THis seems perfect. Was wondering if you could help out on the following question: http://stackoverflow.com/questions/2653096/why-use-mvvm
LnDCobra
Thanks for that! I researched MVVM and now decided to implement. But thanks for that binding Example! Wish I could give you more rep.
LnDCobra
No problem. I'm glad I was able to help!
Brent