开发者

Serialize a view model in Silverlight on Windows Phone 7

I have Silverlight application for the Windows Phone. When the app tombstones, I want to store the current view model. First, where do I store the view model?

  1. The phone application service (I don't know when this lives / dies)
  2. Isolated Storage

I am pretty sure that I should store my view model in isolated storage. My problem is, I get an error when I try to put it in isolated storage. The error says:

Type 'MyViewModel' cannot be serialize开发者_运维技巧d. Consider marking it with the DataContractAttribute and marking all of its members you want serialized with the DataMemberAttribute attribute.

My problem is, I have a LOT of members in this view model. At the same time, it has child objects which have members as well. It just feels like this dirties up my code. It seems odd that I can successfully place the view model in the PhoneApplicationService without any problem. However, I only get this error when I try to put it into isolated storage.

How do I overcome this? I just want to preserve the view model during tombstoning. Thanks!


PhoneAppService State will not persist data if the app gets terminated some time after being tombstoned. Iso storage is disk storage, whereas PhoneAppService.State is just a transient state dictionary that survives tombstoning.


Jeff Prosise's Real-World Tombstoning in Silverlight for Windows Phone should tell you pretty much everything you need to know about tombstoning.


First, do you really need to persist the entire VM? This may be something you need for your app; but I would still ask that you consider persisting only the bits you absolutely require and re-instantiate your VM as needed. That said, Isolated Storage is where you can shove things for persistence.

You could use the IsolatedStorageSettings class to store key-value pair type data. Also, please see here for a complete walkthrough of tombstoning. There is an IsolatedStorageHelper class in the training kit that you could use. It uses a Json serializer/deserializer and should work on most classes with standard type properties. There is also a Tombstone helper in Codeplex here that might work for you.

Hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜