MVVMLight and Data Serialisation

前提是你 提交于 2020-01-14 03:04:08

问题


I'm getting started with MVVMLight for a Windows 8 Store app. I've got the basics working after viewing some videos. however I have run into an issue. Each of my base model classes inherit from ObservableObject in MVVMLight.

This was working fine but I now want to load and save data to XML. So I marked them with DataContract attribute which I'd used previously in a non MVVM implementation. However this now creates an error when serialising as it says my inherited classes must also be marked with this attribute.

As ObservableCollection is compiled in the dll how should I manage this? Will I have to create a set of basic (POCO style) classes which match up with my "ViewModel" style ones and handle the mapping between these. Or is there a better way?


回答1:


You don't want to serialize your viewmodels, you want to serialize their current state so that they can rebuild themselves when the app is restarted.

So, something like this:

public class ViewModelFoo
{
    public ViewModelFoo(ISerializationService serializationService)
    {
         _serializationService=serializationService;
         LoadDefaultData();
    }

    private void LoadDefaultData()
    {
        //Do all your loading of static data here
         FooItems=GetFooItems();
         if(_serializationService.ContainsSerializedState)
         {
              LoadSerializedState();
         }
    }

    public Observable<Foo> FooItems{get;set;}

    public Foo SelectedFooItem
    {
        get{return _fooItem;}
        set{_fooItem=value;
            RaisePropertyChanged("SelectedFooItem"); 
            _serializationService.SelecetedFooItem=value;
           }
    }

    private void LoadSerializedData()
    {
        SelectedFooItem=_serializationService.SelectedFooItem;
        ReloadData();
    }

    private void ReloadData()
    {
        //load whatever data you need.  You've now got your app back into the state it was when it was serialized;
    }
}

Basically, we're updating the state object every time we change something on the screen. We would save the state object when we suspended the app (the event in the App class).

By doing this we're able to store the state of our viewmodel rather than the viewmodel itself. Because we control the serialization service we can save our data using whatever serialization method we want to use.




回答2:


Using Json.Net allows to serialize and deserialize classes based on GalaSoft.MvvmLight.ObservableObject. If you can use this library it seems to be the simplest solution.



来源:https://stackoverflow.com/questions/14245569/mvvmlight-and-data-serialisation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!