Skip navigation

Bill Kempf, a fellow WPF Disciple, was lamenting the fact that by default a CommandBinding can only refer to a handler defined in the code behind of the Window/Page/UserControl in which it’s defined. He wished that a syntax similar to the following was possible

 

<Window>
    <Window.CommandBindings>
        <CommandBinding Command="foo:MyCommands.FooCommand" Executed="{Event Target={StaticResource MyPresenter}, Handler=OnFooCommand}"/>
    </Window.CommandBindings>
</Window>

I took that scenario as my starting point. The first issue I saw was that I needed a markup extension that let’s you specify a Target Object and the name of a handler on that Target returning a ExecutedRoutedEventHandler. So I made one.

The Markup Extension exposes two properties: Target (of type object) and Handler of Type String. The ProvideValue override (shown below) uses reflection to get a handle on the function and creates a lambda that invokes it for the result. (I love lambdas as much as I loved anon functions before them.)

public override object ProvideValue(IServiceProvider serviceProvider)
{
    ExecutedRoutedEventHandler retval=null;
    if (Target == null)
    {
        throw new Exception("Target cannot be Null.");
    }
    var type = Target.GetType();
    var function = type.GetMethod( Handler, new[]{typeof (Object),typeof (ExecutedRoutedEventArgs)});
    if (function != null)
    {
        retval = ((obj, args) => function.Invoke(Target, new[] {obj, args}));
    }
    return retval;
}

So I plug my new markup extension into a sample window, anticipating some good command routing lovin’. Of course it’s never as easy as it looks at first. The Executed property on CommandBinding, although an event, expects a string in markup (the XAML compiler does some trickery to turn the string into an event handler). Well I know, I’ll create an Attached Property to do my magic…

(To be continued…)

Advertisements

One Comment

  1. Thanks for the tease, Mike!  :)Looking forward to the full solution…Josh


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: