DelegateCommand<char> throws NullReferenceException

Jun 9, 2011 at 4:55 AM

The following command binding is failed, how can I avoid it ?

public DelegateCommand<char> PressKeyCommand

<Button Content="1" Command="{Binding Path=PressKeyCommand}" CommandParameter="{Binding Path=Content, RelativeSource=Self, Converter={StaticResource charConverter}}" />

The rest parts of code are following the mvvmtoolkit samples.
DelegateCommand and DelegateCommand<string> are OK

The cause of exception is : DelegateCommand<T>::bool CanExecute(object parameter), while parameter = null.

The Exception message is below:

System.NullReferenceException was unhandled by user code
  Message=Object reference not set to an instance of an object.
       at SimpleMvvmToolkit.DelegateCommand`1.CanExecute(Object parameter) in C:\Projects\SimpleMvvmToolkit\Download\SimpleMvvmToolkit\Toolkit\Helpers\Project\Silverlight\SimpleMvvmToolkit\GenericDelegateCommand.cs:line 43
       at System.Windows.Controls.Primitives.ButtonBase.UpdateCanExecute()
       at System.Windows.Controls.Primitives.ButtonBase.OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
       at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
       at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
       at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
       at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
       at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
       at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
       at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(Object inst, XamlMember property, Object value)

Jun 9, 2011 at 7:54 PM

I think there may be a problem with your converter returning null.  Since you are using WPF, you don't need a value converter at all.  Just pass in the char for the command parameter.  You can set it explicitly using property element syntax, or you can bind the Content of the button to a char property on the ViewModel.  If you like, you can send me the project and I'll have a look:



Jun 14, 2011 at 2:21 PM

It looks like the parameter to CanExecute will be null if it is a value type and there is no method supplied.  So I added null handling to the delegate command.  Here is the latest source code which includes the fix.  I will incorporate this into the next release of the toolkit.  Thanks for bringing this to my attention!