ninja hedgehog
ninja hedgehog

Reputation: 405

ViewModel Handling Events

I saw an question here where OP asked about binding events to ViewModel. Basically ViewModel shall respresent an abstract View containing necessary data from Model so that the View may be also able to use Bindings. But to be able to fullfill all that the ViewModel must also conver most of the use cases which are happening in the View such as example if search textbox is empty the search button shall be greyed out. That works fine but lets add events to the game. It would be way easier if Button.Click where bindable to an EventHandler in ViewModel and inside the event handler you would be then able to use model objects.

Now my question is since WPF supports event driven programming why cant events be handled in ViewModel? How could I provide binding events funcionality?

Upvotes: 1

Views: 387

Answers (2)

MoonKnight
MoonKnight

Reputation: 23833

It is because the use of event explicitly breaks the MVVM pattern (as I am sure you are aware). However there is another way around this - by using the Attached Command Behaviour pattern. More information here.

Code for a small but great framework for attached commands is downloadable from here.

I hope this helps.


Edit. attached behaviour allow you to use events without breaking the MVVM pattern. The use is like

<Border Background="Yellow" Width="350" Margin="0,0,10,0" Height="35" CornerRadius="2" x:Name="test"> 
    <local:CommandBehaviorCollection.Behaviors>
        <local:BehaviorBinding Event="MouseLeftButtonDown" 
                               Action="{Binding DoSomething}" 
                               CommandParameter="An Action on MouseLeftButtonDown"/> 
        <local:BehaviorBinding Event="MouseRightButtonDown" 
                               Command="{Binding SomeCommand}" 
                               CommandParameter="A Command on MouseRightButtonDown"/>
    </local:CommandBehaviorCollection.Behaviors> 
    <TextBlock Text="MouseDown on this border to execute the command"/> 
</Border>

Upvotes: 1

devdigital
devdigital

Reputation: 34349

Event handlers would sit in the view's code behind file. If you're using MVVM, then you'll want to minimise the amount of code in a code behind file.

WPF supports commanding, and the ICommand interface includes a CanExecute and Execute method. There are implementations of ICommand which allow these methods to be implemented on the view model.

Having said that, commanding also has its limitations, so you should consider using an MVVM framework when using MVVM. Something like Caliburn.Micro comes with Actions which also allow verbs on the view model to be invoked based on control events.

Upvotes: 1

Related Questions