如何将数据绑定到用户定义类型的下拉列表?
我有一个下拉列表,其中包含一周中的几天 - 周一到周日。它填充了用户定义类型的两个值,将一周中的数字日期映射到其名称。
Public Structure WeekDays
Public ID As Integer
Public Text As String
Public Overrides Function ToString() As String
Return Me.Text
End Function
End Structure
我想要绑定到的对象有一个整数属性 DayOfWeek,并且我想将下拉列表中所选项目的 ID 值绑定到该对象的 DayOfWeek 属性。例如。用户选择星期四,并将 ID 4 传递给该对象。
在代码中,我可以检索 SelectedItem 的 UDT,但我无法确定要绑定到组合框上的哪个属性。
- 如果我将 UDT 直接添加到下拉列表的 Items 集合中,则 SelectedValue 为 Nothing。
- 如果我将 UDT 添加到 List(Of UDT) 集合并将其设置为下拉列表的数据源,将 ValueMember 设置为 ID,将 DisplayMember 设置为 Text,则 SelectedValue 返回整个 UDT,而不是 ValueMember 属性中指示的 ID。
数据绑定似乎非常适合纯文本框,但在处理更复杂的控件时似乎变得更加挑剔。
更新:我正在寻找的是绑定声明。例如。两者都……
oB = New Binding("SelectedItem", Payroll, "DayOfWeek")
oB = New Binding("SelectedItem.ID", Payroll, "DayOfWeek")
不起作用。第一个被忽略(可能是因为 SelectedItem 属性为 Nothing),第二个失败并出现“无法绑定...”错误。
I have a dropdown list containing the days of the week - Monday to Sunday. It is populated with a user defined type of two values that map the numeric day of the week to it's name.
Public Structure WeekDays
Public ID As Integer
Public Text As String
Public Overrides Function ToString() As String
Return Me.Text
End Function
End Structure
The object I want to Bind to has an integer property DayOfWeek, and I want to bind the ID value of the selected item in the dropdown to the DayOfWeek property on the Object. eg. The user selects Thursday, and the ID of 4 is passed to the object.
In code I can retrieve the UDT of the SelectedItem, but I can't work out which property on the combo box to bind to.
- If I add the UDTs directly to the Items collection of the dropdown, the SelectedValue is Nothing.
- If I add the UDTs to a List(Of UDT) collection and set that as the dropdown's datasource, with the ValueMember set to ID and DisplayMember set to Text, the SelectedValue returns the whole UDT, not the ID as instructed in the ValueMember property.
Databinding seems to work really well for plain textboxes, but it seems to get way more pernickety when dealing with more complex controls.
Update: What I am looking for is the Binding statement. eg. Neither...
oB = New Binding("SelectedItem", Payroll, "DayOfWeek")
oB = New Binding("SelectedItem.ID", Payroll, "DayOfWeek")
... works. The first is just ignored (possibly because the SelectedItem property is Nothing), and the Second fails with a "Cannot bind..." error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
创建属性,
Create Properties,
好的,所以我找到了一个可能的解决方案。
我创建了自己的 ComboBox 控件,该控件继承标准 WinForms.ComboBox 并添加了一个名为 SelectedID 的额外 Integer 属性。
这允许我绑定到 SelectedID 属性...
...并且似乎工作正常。
OK, so I've found a possible solution.
I've created my own ComboBox control that inherits the standard WinForms.ComboBox and added an extra Integer property called SelectedID.
This allows me to bind to the SelectedID property...
...and seems to be working ok.