Best method for Binding 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}
当用户点击编辑公司时,会出现一个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 的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:绑定 ComboBox 的最佳方法
基础教程推荐
- Moq It.Is<>不匹配 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
