WPF PRISM DelegateCommand Wrappers in .NET 4.5

November 27, 2012

tags: ,
2 comments

If you happened to implement an ‘ICommand’ for your presentation logic in WPF, and decided to contain PRISM’s DelegateCommand within your class and use its own mechanism of the ‘CanExecuteChanged’ event – Beware!

Consider the following example –

class CommandWrapper : ICommand
{
    private readonly DelegateCommand _command;

    public CommandWrapper(Action execute, Func<bool> canExecute)
    {
        _command = new DelegateCommand(execute, canExecute);
    }

    public bool CanExecute(object parameter)
    {
        return _command.CanExecute(parameter);
    }

    public void Execute(object parameter)
    {
        _command.Execute(parameter);
    }

    public void RaiseCanExecuteChanged()
    {
        _command.RaiseCanExecuteChanged();
    }

    public event EventHandler CanExecuteChanged
    {
        add { _command.CanExecuteChanged += value; }
        remove { _command.CanExecuteChanged -= value; }
    }
}

.NET 4.5 isn’t compatible with this approach! (With wrappers to any ICommand implementation)

If you upgrade to .NET 4.5, you will see that the UI doesn’t respond in case you raise the ‘CanExecuteChanged’ event in this scenario.

There’s actually an opened support ticket on that – Backward Compatibility Problem in .NET 4.5: WPF / ICommand sender / WeakEventManager

I fixed it in our products by simply inheriting from DelegateCommand, instead of containing it.

You can download a sample project which demonstrates the problem. You can see it happens when the project is compiled to .NET 4.0 or 4,5, but it is actually working well when it is compiled to .NET 3.5.

Update: Luckily Microsoft identified it as a bug and provided a global update that fixes this issue and many others.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

2 comments

  1. tietrinnyMay 15, 2013 ב 18:47

    I’d have to check with you here. Which is not something I commonly do! I take pleasure in reading a post that will make folks believe. Also, thanks for permitting me to comment!

    [URL=http://www.lululemonoutletcheap.com/lululemon-bottoms/lululemon-wunder-under-pants.html]lululemon outlet[/URL]

    Reply
  2. tietrinnyMay 15, 2013 ב 19:42

    I was really pleased to come across this web-site.I wanted to thanks for your time for this splendid read!! I surely enjoying each little bit of it and I’ve you bookmarked to have a look at new stuff you weblog post.

    [url=http://cheapsredsoleshoesa.eu5.org/]red bottom sandals[/url]

    Reply