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

查看:14
本文介绍了绑定 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}

当用户点击编辑公司时,会出现一个TextBox来编辑公司名称,同时还会出现一个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天全站免登陆