So I have a simple setup, an autocompletebox with its Populating event that I want to bind to a command. I use
clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity
(is there a better namespace for doing this?)
It’s not a big deal to bind it, the big deal is to pass that PopulatingEventArgs argument to the bound command.
So how do I do it according to the best practices of PRISM in particular and MVVM in general?
There is no built-in way, so here is how I do it:
The classic Interaction trigger is used like this:
We can’t access the
EventArgsof theMouseEnterevent through binding, so we’re going to have to modify the piece that tosses it away.As it happens, that piece is the
InvokeCommandAction.“So we’re just going to subclass it and override a convenient method that was waiting for us all along” is what I’d have liked to write. But the class is sealed.
So we’re going to have to subclass its parent (abstract) class:
TriggerAction<DependencyObject>The most basic implementation is:
And that
parameteris yourEventArgs!But hold on, it’s not that simple, we have to reproduce the behavior of a regular
InvokeCommandAction.Through Reflector, I decompiled it (but you could go look at the official source, I’m just lazy).
We’re not going to care about the
CommandParameterdependency property, we’re going to assume that if you use this instead ofInvokeCommandAction, you actually want theEventArgsevery time.Here goes the full class (WPF only, see EDIT for SilverLight):
As with any code you fetch from the internet, I highly recommand reading through the whole class, and trying to understand what it does. Don’t just toss it into your app.
Now we can do:
And the code behind:
And that’s a wrap 😉
EDIT: For SilverLight, use this code instead:
But please note that it is less safe than using the full fledged WPF version (doesn’t check types, can crash with frozen elements).