RelayCommand and tombstoning

Apr 1, 2011 at 7:18 PM

Hi,

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 ?

Thanks!

Yacine 

Apr 1, 2011 at 7:23 PM
Edited Apr 1, 2011 at 7: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
{
    get
    {
        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 7: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.

Thanks!