开发者

Is there any general procedure to implement command in MVVM if the element doesn't support command?

Is there any particular way to implement开发者_运维知识库 command in MVVM if the element doesn't support Command. Example how to implement the TextChanged_event for the TextBox?.


There is no need to use the TextChanged_event or the SelectionchangedEvent as you can achieve the same using binding them to your ViewModel properties and waiting for their notification message (check MVVMLight's Messenger helper class).

If you desperately need a handler for those events, you can try the EventToCommand behaviour helper class which uses RelayCommand

You can check out this illustration and example program for details on messenger class and this example for getting a clear picture on EventToCommand behaviour


What you do is watch for the change in your ViewModel's property set method.

The XAML would look something like this:

        <TextBox Text="{Binding  Mode=TwoWay, 
                                 Path=ViewModelProperty,
                                 UpdateSourceTrigger=PropertyChanged}" />

And on the ViewModel class, you define a property like this:

    Private _ViewModelProperty As String
    Public Property ViewModelProperty As String
        Get
            Return _ViewModelProperty

        End Get
        Set(ByVal value As String)
            ' your test for "TextChanged" goes here
            If value <> _ViewModelProperty Then
                _ViewModelProperty = value
                OnViewModelPropertyChanged()
            End If
        End Set
    End Property
    Private Sub OnViewModelPropertyChanged()
        ' logic for handling changes goes here
    End Sub

This has the side effect of executing OnViewModelPropertyChanged() every time you assign a new value to the ViewModelProperty, but you can avoid that by assigning to the backing field instead of the property.

Otherwise, you're implementing ICommand interfaces, which have their use; it depends on how complex you need things to get.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜