Customizing ViewModel State Preservation

,

A viewmodel has the opportunity to customize how its state is persisted by overriding the SaveState method from the ViewModelBase class, as shown:

public override void SaveState(
    IDictionary<string, object> persistentDictionary,
    IDictionary<string, object> transientDictionary)
{
    base.LoadState(persistentDictionary, transientDictionary);
    byte[] state = Serialize(items);
    transientDictionary[itemsStateKey] = state;
    transientDictionary[queryStateKey] = lastQuery;
}

The Serialize and Deserialize methods of the ViewModelBase class are able to convert an object to and from an array. The serialization mechanism is discussed in more detail in the next section.

Conversely, a viewmodel may restore its own state by overriding the LoadState method, as shown in the following example:

public override void LoadState(
    IDictionary<string, object> persistentDictionary,
    IDictionary<string, object> transientDictionary)
{
    base.SaveState(persistentDictionary, transientDictionary);
    object state;
    if (transientDictionary.TryGetValue(itemsStateKey, out state))
    {
        byte[] bytes = state as byte[];
        Items = Deserialize<ObservableCollection<Item>>(bytes);
    }

    if (transientDictionary.TryGetValue(queryStateKey, out state))
    {
        lastQuery = (string)state;
        SearchText = lastQuery;
    }
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.121.156