绑定ComboBox的最佳方法 [英] Best method for Binding ComboBox

查看:101
本文介绍了绑定ComboBox的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将要开发一个大型项目,其中将包含大量的ComboBox。

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.

例如。

我有以下2个

公司{CompanyID,CompanyName,MainContact}

联系人{ContactID,ContactName}

Company {CompanyID, CompanyName, MainContact}
Contacts {ContactID, ContactName}

然后,当用户单击以编辑公司时,将在其中使用文本框来编辑公司名称,同时还会在其中使用ComboBox。

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.

我目前的操作方式是将ComboBox绑定到Contacts数据集,并手动更新后面代码中的Company MainContact字段。

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.

反正我仍然可以绑定选择项目到XAML中的Company MainContact字段中,然后选择项目到ContactName中,并消除后面的代码?

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?

原因是当您开始在整个范围内制作100个组合框时一种

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.

这是否有可能?

推荐答案

首先,我强烈建议您为应用程序使用MVVM设计模式。单独在MVVM应用程序中进行数据绑定和命令将为您节省大量时间。

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"/>

如您所见,ItemsSource绑定到您的联系人数据集,但是当用户选择一个列表中的项目,它将使用所选联系人更新Company.MainContact字段。

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.

这篇关于绑定ComboBox的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆