VB.NET WPF TextBox與類對象綁定

REM TextBox類 :TextBoxCdrObjWidth 和 TextBoxCdrObjHeight
    Dim CdrObjSize As  New CdrObjectSizeClass() ' 要綁定的數據類
Try
            Dim BindingWidth As New Binding
            Dim BindingHeight As New Binding
            BindingWidth.Source = CdrObjSize
            BindingWidth.Mode = BindingMode.TwoWay 
   'BindingMode.TwoWay雙向綁定,即修改TextBox.Text屬性,源目標變量發生改變,更源目標變量改變時PropertyChaned,TextBox.Text屬性也發生改變
            BindingWidth.Path = New PropertyPath("WidthSize")
            BindingWidth.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
            TextBoxCdrObjWidth.SetBinding(TextBox.TextProperty, BindingWidth)
           '代碼透透氣---------分隔線-----------------------------------------------------------------------------
            BindingHeight.Source = CdrObjSize
            BindingHeight.Mode = BindingMode.TwoWay '雙向綁定
            BindingHeight.Path = New PropertyPath("HeightSize")
            BindingHeight.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
            TextBoxCdrObjHeight.SetBinding(TextBox.TextProperty, BindingHeight)
        Catch ex As Exception
            MsgBox(ex.Message)
End Try
REM ----------------------------------------------------------------------------------------------------------------------------------------
‘添加屬性更改接口,實現雙向數據綁定:
在Public Class CdrObjectSizeClass類中添加
Imports System.ComponentModel
Public Class CdrObjectSizeClass
    Implements INotifyPropertyChanged '提供接口,屬性更改通知
    Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged '聲明事件
    '使用Get 和 Set傳值與主窗口TextBox數據綁定
    Public Property HeightSize As String
        Get
            Return CStr(Height)
        End Get
        Set(ByVal value As String)
            If value <> Height Then
                RaiseEvent PropertyChanged(Me, New System.ComponentModel.PropertyChangedEventArgs("HeightSize"))
            End If
            Height = CDbl(value)
        End Set
    End Property
 REM注意,用雙引號即觸發HeightSize對象本身(真正Me.PropertyChanged屬性的更改,不帶雙引號即是傳遞HeightSize的Double值,並沒有真正把事件傳給TextBox綁定數據更新:即BindingHeight.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章