Best method for Binding ComboBox

£可爱£侵袭症+ 提交于 2019-12-11 12:03:17

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/2652166/best-method-for-binding-combobox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!