页面导航 页面内容的保存,
在页面导航中, ,通过后退按钮,不会new 一个page对象,通过后退按钮页面的内容不会有丢失 ,但是通过
private void button1_Click(object sender, RoutedEventArgs e)
{
this.NavigationService.Navigate(new System.Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
}
这种方式导航的都会new 一个新page ,之前页面的 数据都会丢失,为了解决
this.NavigationService.Navigate(new System.Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));这种导航方式数据丢失的问题,提供一下解决方案,创建下面这个类
public class Setting<T>
{
string name;
T value;
T defaultValue;
bool hasValue;
public Setting(string name, T defaultValue)
{
this.name = name;
this.defaultValue = defaultValue;
}
public T Value
{
get
{
// Check for the cached value
if (!this.hasValue)
{
// Try to get the value from Isolated Storage
if (!IsolatedStorageSettings.ApplicationSettings.TryGetValue(
this.name, out this.value))
{
// It hasn't been set yet
this.value = this.defaultValue;
IsolatedStorageSettings.ApplicationSettings[this.name] = this.value;
}
this.hasValue = true;
}
return this.value;
}
set
{
// Save the value to Isolated Storage
IsolatedStorageSettings.ApplicationSettings[this.name] = value;
this.value = value;
this.hasValue = true;
}
}
public T DefaultValue
{
get { return this.defaultValue; }
}
// "Clear" cached value:
public void ForceRefresh()
{
this.hasValue = false;
}
}
在需要保存数据的页面里定义这么一个字段
Setting<int> savedCount = new Setting<int>("SavedCount", 1);
然后 在导航出去之前 ( protected override void OnNavigatedFrom(NavigationEventArgs e)) 给savedCount 赋值
this.savedCount.Value = “something”
最后在导航进来的时候 (OnNavigatedTo事件)里面读取savedCount 里面的值
this.count = this.savedCount.Value;
通过对setting里面代码的看一眼里面用到了 IsolatedStorageSettings.ApplicationSettings[this.name]。