The problem: I would like to bind an event to a public method of the ViewModel
via XAML.
The notorious solution is to create a public ICommand
property on the ViewModel
that returns a RelayCommand
or a DelegateCommand
and then to use EventTrigger
and InvokeCommandAction
from Windows.Interactivity
in XAML to bind the event to the command. Very similar alternative is to use MVVMLight's EventToCommand
, which even provides the possibility to pass EventArgs
as the Command's parameter.
This solution has the pitfall of being too verbose, and hence makes the code hard to refactor and maintain.
I would like to use an MarkupExtension for binding an event to a public method of the ViewModel
directly. Such a possibility is provided by the EventBindingExtension
from this blog post.
Example usage in XAML:
<Button Content="Click me" Click="{my:EventBinding OnClick}" />
Where the ViewModel has the following method:
public void OnClick(object sender, EventArgs e)
{
MessageBox.Show("Hello world!");
}
I have a few questions regarding this approach:
- I have tested it and it works like a charm for me but since I am no expert I would like to ask if this solution does have some pitfalls or possibly unexpected behaviors.
- Is this in compliance with the MVVM pattern?
EventBindingExtension
requires the public method it is bound to to match the parameters of the event. How could it be extended to allow theobject source
parameter to be omitted?- What other MarkupExtensions similar to this are there available in frameworks for WPF or NuGet packages?