Windows中的自定义逻辑形成数据绑定

时间:2014-09-30 23:45:01

标签: winforms mvvm

刚从带有Knockout.js的Web开发转移到Windows窗体,我正在读取绑定,我的目标是实现类似于Knockout的MVVM架构,但是在windows窗体中。

那就是说,我在尝试在控件的绑定上应用自定义逻辑时遇到了麻烦,我希望例如将错误标签的Visible属性绑定到ViewModel类中名为IsValid的函数的结果

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

Winforms(vb.net代码)中的下一个DataBinding示例有什么问题:

Public Class Info
    Implements INotifyPropertyChanged

    Private _Word As string
    Public Property Word As String
        Get
            Return _Word
        End Get
        Set(value As String)
            If value.Equals(_Word) = False Then
                _Word = value
                Me.NotifyPropertyChanged("Word")
            End If
        End Set
    End Property


    Public Event PropertyChanged(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged

    Private Sub NotifyPropertyChanged(propertyName As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
    End Sub

    Public Sub New(newWord As String)
        Me.Word = newWord
    End Sub

    Public Function IsValid() As Boolean
        Return (String.IsNullOrEmpty(Me.Word) = False)
    End Function
End Class

表格的代码

Public Class frmInfo
    Private _info As Info

    Public Sub New(inInfo As String)
        InitializeComponent()
        _info= New Info(inInfo)
    End Sub

    Private Sub frmInfo_Load(sender As Object, e As EventArgs) Handles Me.Load
        Me.txtID.DataBindings.Add("Text", _info, "Word") 'Add DataBinding for Word property
        'Binding label Visible property to result of the IsValid function
        Dim bind As New Binding("Visible", _info, "Word")
        AddHandler bind.Format, Sub(obj As Object, args As ConvertEventArgs) args.Value = _raha.IsValid()
        Me.lblEven.DataBindings.Add(bind)
    End Sub

End Class