【问题标题】:Binding a ComboBox SelectedValue to a Nullable(Of Integer) property throws InvalidCastException将 ComboBox SelectedValue 绑定到 Nullable(Of Integer) 属性会引发 InvalidCastException
【发布时间】:2018-08-15 02:14:33
【问题描述】:

我有一个 ViewModel 类(实例化为 ilvm),上面有一个 Nullable(Of Integer) 属性,称为 LinkedCompanyID,它手动绑定到 ComboBox 上的 SelectedValue。用户从列表中选择一个值会导致组合框引发 InvalidCastException。我以前用其他类做过这个,不同之处在于它们是通过 BindingSource 绑定的,而不是如下所示的直接绑定。我必须直接绑定的原因是该类是从 ComponentModel 派生的,它似乎使各个属性对 BindingSource 不可见。

<Browsable(False), Bindable(True)>
<DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)>
Public Property LinkedCompanyID As Integer?
    Get
        If Not DesignMode AndAlso _currentEntity IsNot Nothing Then
            Return _currentEntity.LinkedCompanyID
        Else
            Return Nothing
        End If
    End Get
    Set(value As Integer?)
        If Not DesignMode AndAlso _currentEntity IsNot Nothing Then
            If Not EqualityComparer(Of Integer?).Default.Equals(_currentEntity.LinkedCompanyID, value) Then
                _currentEntity.LinkedCompanyID = value
                NotifyPropertyChanged("LinkedCompanyID")
            End If
        End If
    End Set
End Property

绑定形式为Load事件:

.
.
.

        Dim linkedCompanyBinding As Binding = New Binding("SelectedValue", ilvm, "LinkedCompanyID", False, DataSourceUpdateMode.OnPropertyChanged)
        AddHandler linkedCompanyBinding.Parse, AddressOf parseNullableInteger
        Me.cmbLinkedCompany.DataBindings.Add(linkedCompanyBinding)

列表定义为:

IEnumerable(Of KeyValuePair(Of integer?, string))

DisplayMember 设置为“Value”,ValueMember 设置为“Key”。

当用户从组合框列表中选择一个值时,会引发 InvalidCastException,指示它无法从 Int32 转换为 Nullable(Of Integer)。

无奈之下我添加了 parseNullableInteger 方法:

Private Sub parseNullableInteger(sender As Object, e As ConvertEventArgs)
    If e.Value IsNot Nothing AndAlso Not IsDBNull(e.Value) Then
        e.Value = Convert.ChangeType(e.Value, e.DesiredType)
    Else
        e.Value = Nothing
    End If
End Sub

这也不起作用,实际上当它尝试将 Integer 转换为 Nullable Integer 时会生成它自己的 InvalidCastException。关于如何使这项工作的任何建议?

谢谢,尼尔

【问题讨论】:

  • 请阅读this。
  • 我花了一些时间处理这个问题,终于意识到,当对象被分配给 BindingSource 的 DataSource 而不是直接将控件值绑定到属性时,这是可行的。 BindingSource 添加了在 ComboBox 值和 Nullable 属性之间转换的魔力。

标签: .net vb.net winforms .net-4.0 vb.net-2010


【解决方案1】:

所以来扩展我的评论。 View Model 作为 DataSource 绑定到 BindingSource,然后控件绑定到 BindingSource,ComboBox 正常工作。

例如

dim ilvmBindingSource as New BindingSource
ilvmBindingSource.DataSource = ilvm
cmbLinkedCompany.DataBindings.Add("SelectedValue", ilvmBIndingSource, "LinkedCompanyID", False, DataSourceUpdateMode.OnPropertyChanged)

这基本上完成了处理来自 ComboBox 的“奇怪”值的工作。

【讨论】:

    猜你喜欢
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 2015-08-23
    • 2010-09-30
    • 2015-03-14
    • 2021-07-07
    相关资源
    最近更新 更多