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

RelayCommand and tombstoning

Apr 1, 2011 at 8:18 PM


i'm stuck with seemingly basic problem, in my WP7 app, when I try to save to phone service state a viewmodel that exposes a couple of RelayCommand properties, I get an exception that says RelayCommand is not serializable. I'm not using ViewModelBase, just RelayCommand from MVVMLight. Tried fiddling with the source code by adding DataContract and DataMember attributes, seems the Action and Func<bool> types are not serializable (of course).

So this means I can't just serialize and deserialize my vm, I need to do extra work to reinitialize the commands after it's deserialized. Any better suggestions ?



Apr 1, 2011 at 8:23 PM
Edited Apr 1, 2011 at 8:24 PM

You should not serialize commands. If you mark all the other members as [DataMember] and ignore the commands they won't be serialized.

Then you can use lazy initialization to instantiate them when needed:


public RelayCommand MyCommand
        if (_myCommand = null)
            _myCommand = new RelayCommand...;
        return _myCommand;


There are other ways, but this one is the simplest that comes to my mind.

Apr 1, 2011 at 8:27 PM

Great suggestion, I had just done the [DataContract] and [DataMember] part, but I was reinitializing the commands in my activation code. Much better to use lazy initialization.