This project is read-only.

MVVM Light and NullReferenceException in AppBarItemCommand

Sep 27, 2011 at 11:13 PM

Hello!

I decided to try out AppBarUtils and everything worked fine, until i integrated it to my WP7-app, which is using MVVM Light -library.

My ViewModels are instantiated by ViewModelLocator and many of the VMs instantiate RelayCommands (which the AppBarButtons are bound to) in their constructors. This caused a null reference in AppBarItemCommand-class at ChangeIsEnabled-method. This method gets called in a phase when _item-field is null. I solved this simply by adding null check to the method.

Thank you for the lib, after that minor fix it's working like a charm!

If my explanation doesn't cover enough ground, i'm ready to provide more info. Also if i'm simply doing it wrong, please do correct me!

Best Regards,

J. Arola

Oct 15, 2011 at 3:51 PM

Same problem here.

Dec 21, 2011 at 12:48 PM
Edited Dec 21, 2011 at 12:48 PM

Thanks for reporting this issue. I did not consider working together with MVVM Light in this way.

When the Command is bound to a property of the current DataContext, the OnAttached method will be invoked before ChangeIsEnabled method. And when using in your scenario, the binding will be set up before OnAttached method. Because the _item is initialized only in OnAttached method, ChangeIsEnabled method will throw.

I've added the check for null inside ChangeIsEnabled method and will publish an updated version soon.

Apr 18, 2012 at 2:53 AM

Hello,@Allen Lee

when i used AppBarUtils in MvvmLight, a problem occured to me.

when the OnAttached function executed,the  _item  variable  was not null  and it had registered the click event successfully!
protected override void OnAttached()
{
_item=AssociatedObject.ApplicationBar.FindItem(Type, Id);

if (_item != null)
{
_item.Click += ItemClick;
}
}
 

after that, in OnCommandChanged function the ChangeIsEnabled  never executed successfully. Because _item was always null.
private void ChangeIsEnabled()
{
if (_item != null)
{
_item.IsEnabled = Command.CanExecute(CommandParameter);
}
}

please tell me why it happened! 

Apr 18, 2012 at 2:34 PM

@Loongzxl When _item is found inside OnAttached, it shouldn't lose its value and cause your issue. Could you send the code to allenlooplee[^#^]yahoo.com.cn so that I can investigate how MVVM Light affects AppBarUtils?

Apr 21, 2012 at 7:54 AM

@Loongzxl I debugged the code you sent to me. ChangeIsEnabled method was called before OnAttached method just like the above discussion, because MVVM Light uses locator model to host view models as static properties.