1

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?.

akjoshi
  • 15,374
  • 13
  • 103
  • 121
Kishore Kumar
  • 21,449
  • 13
  • 81
  • 113

2 Answers2

0

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.

Rob Perkins
  • 3,088
  • 1
  • 30
  • 51
  • what about the ComboBox SelectionchangedEvent... if i want the removed items and added items? – Kishore Kumar Jul 08 '10 at 04:40
  • For that, you have to get into implementing ICommand, if you want your MVVM pattern to stay "pure". If you have no need of that, that is, if you have no UI designers insisting upon there being no code-behind in the XAML, then implement a SelectionChanged event handler right in your code-behind, and use that to call the ViewModel's methods. – Rob Perkins Jul 08 '10 at 16:51
0

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

Community
  • 1
  • 1
Amsakanna
  • 12,254
  • 8
  • 46
  • 58