将对象属性绑定到组合框

时间:2017-01-11 09:10:15

标签: vb.net class oop combobox binding

我正在尝试为<?php use Workerman\Worker; use Workerman\WebServer; use Workerman\Autoloader; use PHPSocketIO\SocketIO; // composer autoload include __DIR__ . '/vendor/autoload.php'; include __DIR__ . '/src/autoload.php'; $io = new SocketIO(2020); $io->on('connection', function($socket){ } 添加Combobox的绑定。该属性是枚举。我设法将class property中的项目加载到enum可能有点非正统但它有效。 (也欢迎改进建议)然后,当表单加载时,Combobox显示活动的性别,所有选项都在下拉菜单中。

但是,当我将Combobox的焦点更改为Combobox以测试结果时,它会恢复为男性(在我的测试中,我想将性别更改为女性)。

如何确保将新的性别值传递给我的对象?

这是我的代码示例

button

1 个答案:

答案 0 :(得分:1)

如果使用数据绑定,则使用ComboBox.DataSource绑定要选择的项目集合,并使用ComboBox.SelectedValue作为选定值

Public Class Form1

    Private _Person As Person

    Public Sub New()
        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

        ' Bound list of enums to the combobox

        Dim genderList As List(Of GenderEnum) = [Enum].GetValues(GetType(GenderEnum))
                                                  .OfType(Of GenderEnum)
                                                  .ToList()
        ComboBox1.DataSource = genderList

        _Person = New Person With { .Gender = GenderEnum.Male }

        // Bound Person.Gender to the ComboBox.SelectedValue
        ComboBox1.DataBindings.Add("SelectedValue", _Person, NameOf(_Person.Gender), True)

    End Sub

    Private Enum GenderEnum
        Male
        Female
    End Enum

    Private Class Person
        Public Property Gender As GenderEnum
    End Class

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Debug.Print(Personobject.Gender.ToString)
    End Sub
End Class

请注意,如果您希望在其他地方更新_person.Gender时更改了组合框选定值,则Person类需要在setter中实现INotifyPropertyChanged接口并引发PropertyChanged事件Gender财产。