Determine Failing Delegate Command for CanExecute

Apr 27, 2009 at 5:00 PM

I have recently changed a delegate command's type from object to Guid.  Now when my applications starts up this block of code errors out:

 

 

bool ICommand.CanExecute(object parameter)

 

{

 

return CanExecute((T)parameter);

 

}

The excetion is this:  Object reference not set to an instance of an object.

My problem is that I have no idea where in my code this problem is occurring.  The call stack shows only two lines the line for the call to CanExecute and   [External Code].

I have reviewed all my xaml to make sure that all instances of a command reference to the Guid typed DelegateCommand also have a CommandParameter binding to a non null Guid.

Can anybody suggest anything that will help root cause this issue?  If anyone can explain when this code is called and what would call it so I can add some breakpoints it would help.

Thanks!
Stewart

Apr 27, 2009 at 6:03 PM
OK.  I figured out the issue and learned a few things in the process that I thought I would share.

1. Pay Attention to When You Initialize Your View - I am using the MVVM pattern for constructing my views.  My ViewModel is taking IView as a parameter in the constructor.  My Views constructor is empty and has one line of code "InitializeComponent();".  This caused all of my data binding in the XAML to happen before my ViewModel was constructed (the unity container was instantiating the view and calling it's constructor before the view model).  To fix this I moved the InitializeComponent(); line of code to the setter property of the ViewModel for the view.  It looks like this:

 

public IKeyNavigatorViewModel Model
{
    
set
    
{    
        
this.model = value;
        
this.DataContext = value;
        InitializeComponent();
    }
}

After this change my XAML binding wasn't occuring until after the ViewModel was constructed and the data context for the view had been set.  Unfortunately, I was still getting the error above.  So my next point:

2.  Set Your CommandParameter Attributes Fist - Turns out I was defining my CommandParameter attribute after my Command attribute in the XAML.  Like so:

 

 

 

<Button Canvas.Left="142" Canvas.Top="323.492"
Command="{Binding NavigateBusinessContextCommand}"
CommandParameter
="{Binding BusinessContextEnvironmentId}"
Cursor
="Hand" Height="25" Opacity="0" Panel.ZIndex="2" Width="80" />

 

 

 

The CanExecute method above is called when the Command attribute is binding; before the CommandParameter is set.  I finally fixed the issue by swapping the order to this:

<Button Canvas.Left="142" Canvas.Top="323.492"
CommandParameter="{Binding BusinessContextEnvironmentId}" 
Command="{Binding NavigateBusinessContextCommand}"
Cursor
="Hand" Height="25" Opacity="0" Panel.ZIndex="2" Width="80" />

 

 

 

 

Hope this heps!
Stewart