This project has moved and is read-only. For the latest updates, please go here.

Using DelegateCommand with parameterized 'CanExecute' not working

Mar 22, 2012 at 5:42 PM

I'm trying to use the DelegateCommand class to control what commands are available on each element of a DataGrid control. My application is based on the techniques used in the Waf Book Library application, so it should be easy to show an example. To emulate my problem I modified the Book Library application to try to control whether the LendToCommand is available on each book. To do this I made the following changes to the code in the BookController class:

// Original code: this.lendToCommand = new DelegateCommand(p => LendTo((Book)p));
this.lendToCommand = new DelegateCommand(p => LendTo((Book)p), p => CanLendTo((Book)p));

...and now add the CanLendTo function like so:

// This is a new method added to the ReportController class
private bool CanLendTo(Book book) { return false; } 

I see the behavior I expect, which is that the LendToCommand is disabled for *every* book in the BookListViewModel. However, what's causing me issue is that the book parameter passed into the CanLendTo method is always null, so I can't make any meaningful decisions about the Command for each book. In my actual application I want to control what Commands are available based on the permissions the current user has. Imagine for the book library that some users can lend out books by a specific author, but other can not. From what I can tell the DelegateCommand class seems to support this, but I'm new to WPF so is there something obvious I'm missing here?

Thanks for any insight anyone can provide.

Mar 25, 2012 at 9:18 PM

I have experienced a similar issue once. It seems that the CanExecute method is called before the Binding of the Command Parameter is evaluated. That is the reason why the parameter is null at the first time. If the CanExecute method is called again then the parameter is not null anymore (but this might not happen).

Here is a bug entry regarding this WPF bug:

Mar 26, 2012 at 2:05 PM

Thank you for the reply. After some further research based on what you highlighted I'm going forward with a workaround shown here:

It's not perfect, because it sometimes requires a mouse click for the command to refresh the CanUpdate status, but I think it will work for my needs. It's just too bad this doesn't just work cleanly, because it's a straightforward and useful feature.