如何阻止绑定到业务对象的自定义控件不必要地更新?

时间:2010-12-16 06:06:00

标签: winforms data-binding custom-controls

我有一个带有自定义控件的Windows窗体应用程序,用于输入日期。这是从Textbox继承的,并实现了一个Value属性,用于绑定到底层业务对象。

除了控件验证它更新绑定属性(即使它没有更改)时,一切都运行良好。这是一个问题,因为我正在使用实体框架,并且对实体属性的更改会导致每次用户打开时关闭数据库中的相应字段,并关闭托管此控件的表单。

以下是代码:

Public Class TextBoxDate
Inherits TextBox

Public ValueChanged As EventHandler

Private _dateValue As Nullable(Of Date) = Nothing
<Bindable(True)> _
<Category("Appearance")> _
Public Property Value() As Nullable(Of Date)
    ' Bind to the Value property instead of the Text property, as the latter will not allow
    ' the user to delete the contents of the textbox. The Value property provides support for nulls.
    Get
        Value = _dateValue
    End Get
    Set(ByVal value As Nullable(Of Date))
        _dateValue = value
        ' Update the text in the textbox
        If value.HasValue Then
            Text = CDate(value).ToShortDateString
        Else
            Text = vbNullString
        End If
        OnValueChanged()
    End Set
End Property

Private Sub OnValueChanged()
    If (ValueChanged IsNot Nothing) Then
        ValueChanged(Me, New EventArgs())
    End If

End Sub

Private Sub TextBoxDate_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Enter

    _userEntered = True

End Sub

Private Sub TextBoxDate_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Leave

    _userEntered = False

End Sub

Protected Overrides Sub OnValidating(ByVal e As System.ComponentModel.CancelEventArgs)

    If _userEntered Then
        If Me.TextLength = 0 Then
            ' Null value will be saved to the database via the bound Value property
            If Value IsNot Nothing Then
                Value = Nothing
            End If
        Else
            Dim dateValue As Date
            If Date.TryParseExact(Text, "d/M/yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo, Globalization.DateTimeStyles.None, dateValue) Then
                If Value Is Nothing Or (dateValue <> Value) Then
                    Value = CDate(Text)
                End If
            Else
                e.Cancel = True
            End If
        End If
    End If

    MyBase.OnValidating(e)

End Sub

End Class

这让我很生气。任何帮助将不胜感激。

斯科特

1 个答案:

答案 0 :(得分:0)

定义文本框的绑定时,可以指定Binding对象的DataSourceUpdateMode,例如

Binding custNameBinding = new Binding("Text", ds, "customers.custName");
custNameBinding.DataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged;
custNameTextBox.DataBindings.Add(custNameBinding);

MSDN文档说“只要控件属性的值发生更改,就会更新数据源。”