Monday, January 14, 2013

Silverlight twoway binding helper

For real twoway binding on textbox of silverlight, you have to define a helper class and implement INotifyPropertyChanged


Partial Public Class SKUDetailUserControl
    Inherits UserControl
    Implements INotifyPropertyChanged


    ''Define multiple for two way mode
    Public Event PropertyChanged(ByVal sender As Object, ByVal e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged


Helper class:



    Public Class BindingHelper
        Public Shared Function GetUpdateSourceOnChange(obj As DependencyObject) As Boolean
            Return obj.GetValue(UpdateSourceOnChangeProperty)
        End Function
        Public Shared Sub SetUpdateSourceOnChange(obj As DependencyObject, value As Boolean)
            obj.SetValue(UpdateSourceOnChangeProperty, value)
        End Sub
        Public Shared ReadOnly UpdateSourceOnChangeProperty As DependencyProperty =
        DependencyProperty.RegisterAttached("UpdateSourceOnChange", GetType(Boolean), GetType(BindingHelper), New PropertyMetadata(False, AddressOf OnPropertyChanged))

        Private Shared Sub OnPropertyChanged(obj As DependencyObject, e As DependencyPropertyChangedEventArgs)
            Dim TxtBox As TextBox = obj
            If TxtBox IsNot Nothing Then
                If e.NewValue Then
                    AddHandler TxtBox.TextChanged, AddressOf OnTextChanged
                Else
                    RemoveHandler TxtBox.TextChanged, AddressOf OnTextChanged
                End If
            End If
        End Sub
        Private Shared Sub OnTextChanged(sender As Object, e As TextChangedEventArgs)
            Dim TxtBox As TextBox = sender
            If TxtBox IsNot Nothing Then
                Dim be = TxtBox.GetBindingExpression(TextBox.TextProperty)
                If be IsNot Nothing Then
                    be.UpdateSource()
                End If
            End If
        End Sub
    End Class


XAML :




No comments: