Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Event Handling in MVVM

Just wondering what people had for ideas on how best to handle events in a ViewModel from controls on a View ... in the most lightweight way possible.

Example:

<MediaElement
     MediaOpened={Binding SomeEventHandler} />

In this case we want to handle the MediaOpened event in a ViewModel. Without a framework like Prism, how would one bind this to a ViewModel?

like image 368
Chris Nicol Avatar asked Dec 18 '09 03:12

Chris Nicol


People also ask

Is MVVM deprecated?

This is the same MVVM library used by the Microsoft Store, the Photos app, and more! The MVVM Toolkit is inspired by MvvmLight, and is also the official replacement for it now that the library has been deprecated.

What is WPF in MVVM?

The Windows Presentation Framework (WPF) takes full advantage of the Model-View-ViewModel (MVVM) pattern. Though it is possible to create WPF applications without using the MVVM pattern, a little investment in learning can make building WPF applications much simpler.

When should MVVM be used?

MVVM is enough for small projects, but when your codebase becomes huge, your ViewModel s start bloating. Separating responsibilities becomes hard. MVVM with Clean Architecture is pretty good in such cases. It goes one step further in separating the responsibilities of your code base.


2 Answers

Commanding - your 'SomeEventHandler' needs to be a class that implements ICommand... there's a heap of literature available online...

Also - I would consider getting a free, lightweight 'mini' MVVM framework, such as MvvmFoundation, which provides the RelayCommand for just such a purpose (without the complexity/overhead of learning PRISM)

EDIT:

Have a look at this blog for attaching command to any event... It is incredibly powerful, as I mentioned, but I guess you do need to make a judgement call if this is what you want, compared with something like attaching an old-fashioned event, and using a super-slim event handler in your code behind that simply invokes some method on your ViewModel, something like:

public void SomeEventHandler(object sender, SomeEventArgs e)
{
    MyViewModel vm = (MyViewModel)this.DataContext;
    vm.HandleLoadEvent( );
}

pragmatic vs Best-practise... I'll leave it with you ;)

like image 126
kiwipom Avatar answered Nov 09 '22 18:11

kiwipom


Have a look at Marlon Grech's Attached Command Behaviors. It makes it easy to bind events to ViewModel commands

like image 34
Thomas Levesque Avatar answered Nov 09 '22 18:11

Thomas Levesque