|
using System; |
|
using System.Collections.Generic; |
|
using System.IO; |
|
using System.Linq; |
|
using System.Runtime.Serialization; |
|
using System.Windows.Controls; |
|
using Microsoft.Phone.Controls; |
|
using Microsoft.Phone.Shell; |
|
|
|
namespace Linearstar.Alistar.ViewModels |
|
{ |
|
public static class Navigator |
|
{ |
|
const string StateKey = "Navigator"; |
|
static readonly Random r = new Random(); |
|
static Stack<object> stack = new Stack<object>(); |
|
|
|
public static void Load() |
|
{ |
|
if (PhoneApplicationService.Current.State.ContainsKey(StateKey)) |
|
{ |
|
var state = PhoneApplicationService.Current.State[StateKey]; |
|
var dcsl = new Dictionary<Type, DataContractSerializer>(); |
|
|
|
stack = new Stack<object>(((byte[][])state).Select(_ => |
|
{ |
|
using (var ms = new MemoryStream(_)) |
|
using (var br = new BinaryReader(ms)) |
|
{ |
|
var type = Type.GetType(br.ReadString()); |
|
var dcs = dcsl.ContainsKey(type) ? dcsl[type] : dcsl[type] = new DataContractSerializer(type); |
|
|
|
return dcs.ReadObject(ms); |
|
} |
|
})); |
|
PhoneApplicationService.Current.State.Remove(StateKey); |
|
} |
|
} |
|
|
|
public static void Save() |
|
{ |
|
var dcsl = new Dictionary<Type, DataContractSerializer>(); |
|
|
|
stack.Push(((PhoneApplicationPage)((Frame)App.Current.RootVisual).Content).DataContext); |
|
|
|
PhoneApplicationService.Current.State[StateKey] = stack.Select(_ => |
|
{ |
|
var type = _.GetType(); |
|
var dcs = dcsl.ContainsKey(type) ? dcsl[type] : dcsl[type] = new DataContractSerializer(type); |
|
|
|
using (var ms = new MemoryStream()) |
|
using (var bw = new BinaryWriter(ms)) |
|
{ |
|
bw.Write(type.AssemblyQualifiedName); |
|
dcs.WriteObject(ms, _); |
|
|
|
return ms.ToArray(); |
|
} |
|
}).ToArray(); |
|
} |
|
|
|
public static T GetFromStore<T>(PhoneApplicationPage page) |
|
{ |
|
return (T)(page.DataContext ?? stack.Pop()); |
|
} |
|
|
|
public static void Navigate<T>(T viewModel) |
|
{ |
|
GC.Collect(); |
|
|
|
var frame = (Frame)App.Current.RootVisual; |
|
var type = typeof(T).FullName; |
|
var url = "/Alistar;component/" + type.Replace("Linearstar.Alistar.ViewModels", "Views").Replace(".", "/").Replace("ViewModel", "Page.xaml") + "?r=" + r.Next(); |
|
|
|
stack.Push(viewModel); |
|
frame.Navigate(new Uri(url, UriKind.Relative)); |
|
} |
|
} |
|
} |