开发者

Implement storage of data between calls? (C# - WPF)

I have an ALPHA application which allows you grab an obfuscated font from and XPS file and store the .odttf file for use in Silverlight. The application "works" as in it does what it says on the tin, albeit in a very rough sort of way.

In the process of cleaning this tool up to create the BETA I can across an issue. I want the application to be laid out in a wizard style which would gather data from the user, like which font to use, where to save the extracted file, etc.

In the current implementation this is all done in the code behind (Actually it calls a helper class). But implementing a wizard means that each piece of the data is gathered on a different "page". I did not want to simple pass the data around using the page constructors as I am trying to implement MVVM which aims to keep the code behind clean.

I suppose what I am looking for is a data storage in code that persists windows. that way I can grab the data in my window (view), pass it to m开发者_开发百科y viewmodel via binding and sent it down to the windows model(data class) to be stored somewhere.

I could use a database or XML file but that seems like overpowered storage for the few pieces of information I need.

So in summary, is there a way to have an in memory object that persists window calls and can be referenced by multiple models (classes).

Thanks!


Static class or singleton to store your data and access it from all your views?


Best way would be using the same ViewModel for all pages and then serializing it if you want to use it later.

public class MyViewModel
{
    // Properties to be serialized
    public string MyViewModelProperty1 = "";
    public string MyViewModelProperty2 = "";

    // Save to file.
    public virtual bool Save(string viewmodelFilePath)
    {
        try
        {
            Directory.CreateDirectory(Path.GetDirectoryName(viewmodelFilePath));
            StreamWriter write = new StreamWriter(viewmodelFilePath);
            XmlSerializer xml = new XmlSerializer(GetType());
            xml.Serialize(write, this);
            write.Close();
        }
        catch
        {
            return false;
        }
        return true;
    }

    // Load from file.
    public static object Load(Type type, string viewmodelFilePath)
    {
        StreamReader reader;
        object settings;
        XmlSerializer xml = new XmlSerializer(type);

        try
        {
            reader = new StreamReader(viewmodelFilePath);
            viewmodel = xml.Deserialize(reader);
            reader.Close();
        }
        catch
        {
            viewmodel = 
                type.GetConstructor(System.Type.EmptyTypes).Invoke(null);
        }
        return viewmodel;
    }
}

Original code from Petzold book

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜