MVVM & Serialization - How do I access the instanc

2019-08-27 22:21发布

This question already has an answer here:

I'm trying to learn how to serialize objects using the MVVM pattern. I have a MainViewModel which I would like to serialize. The serializer needs an instance of MainViewModel which should be created in my MainView, but I can't figure out how to access it. What are my options here? What would be the best route for me to take to manage to serialize my ViewModels (or Models for that matter)? Would making classes static help or would that just break the pattern (From what I've seen MVVM doesn't seem to be too big on static?

I am an inexperienced programmer (especially when it comes to MVVM), but I really am trying here I'm just at a loss at this point. I would really appreciate any help anybody could give me in figuring out how to serialize my ViewModels and Models.

"<Window.DataContext>
    <local:MainViewModel/>
 </Window.DataContext>

EDIT: More code

    private void SaveGameExecute()
    {
        ObjectSerializer<MainViewModel> objSerializer = new ObjectSerializer<MainViewModel>();
        objSerializer.SaveSerializedObject(this, "Save.sav");
    }

    private void LoadGameExecute()
    {
        ObjectSerializer<MainViewModel> objSerializer = new ObjectSerializer<MainViewModel>();
        /*****/ = objSerializer.GetSerializedObject("Save.sav");
    }

EDIT: Regardless of what it is I need to serialize, can anybody please give me some advice on how to do this using MVVM? If it's models I need to serialize, I still don't know how to access the particular instances of them. If anybody who has experience with serializing MVVM projects, please give me some guidelines of what to do. Without knowing how to locate the instances of the models/viewmodels/etc I don't really know what to do.

1条回答
\"骚年 ilove
2楼-- · 2019-08-27 22:40

I would recommend that you rethink your need to serialize the ViewModel in the first place.

Typically you want to serialize the underlying Model. The ViewModel is just an intermediary, to present the Model data in a way that the View can understand. If your ViewModel contains data which you want to serialize and pass around, you might consider pushing it down, into the Model instead.

For serialization techniques in general, there are many. Refer to the MSDN documentation (there are walkthroughs at the bottom).

查看更多
登录 后发表回答