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?
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.
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.
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.
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 ;)
Have a look at Marlon Grech's Attached Command Behaviors. It makes it easy to bind events to ViewModel commands
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With