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?
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
MediaOpened is an event and does not support command binding.
In order to bind to the event a helper object may be used which attaches to the event and executes a command.
To bind to the view model add a property which implements ICommand. Figure 3 in this MSDN magazine article shows the RelayCommand which is a useful implementation of ICommand. RelayCommand is initialized with a delegate to connect to your view model.
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
The small and opensource ImpromptuInterface.MVVM framework ha an event binding syntax and using the dlr in .net 4.0. Although this example requires subclassing the ImpromptuViewModel. The event binding property doesn't have any dependency on that specific viewmodel type and the eventbinding provider involved is public.
<Window x:Class="MyProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:MVVM="clr-namespace:ImpromptuInterface.MVVM;assembly=ImpromptuInterface.MVVM" Title="MainWindow" Height="600" Width="800">
<MediaElement MVVM:Event.Bind="{Binding Events.MediaOpened.To[MediaElement_MediaOpened]}" />
...
public class MyViewModel{
public dynamic Events
{
get { return new EventBinder(this); }
}
public void MediaElement_MediaOpened(MediaElement sender, RoutedEventArgs e){
...
}
}