【问题标题】:How to stop a custom control bound to a business object from updating unnecessarily?如何阻止绑定到业务对象的自定义控件不必要地更新?
【发布时间】:2010-12-16 06:06:00
【问题描述】:

我有一个带有用于输入日期的自定义控件的 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

这快把我逼疯了。任何帮助将不胜感激。

斯科特

【问题讨论】:

    标签: winforms data-binding custom-controls


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-17
      • 2023-03-31
      • 1970-01-01
      • 2013-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多