【发布时间】:2014-10-22 18:51:32
【问题描述】:
我有 Windows Phone 8.1 应用程序,我需要从一个页面导航到同一页面的新实例。 例如:
主页 -> 画布-?
“画布”在哪里 - xaml 页面, “?” - 实例指南。 我知道在 wp8 中是这样的:
NavigationService.Navigate(new Uri("/Canvas.xaml?guid=" + myGuid, UriKind.Relative));
我在 MainPage.cs.Xaml 中编写了这段代码:
private void addNewCanvas_Click(object sender, RoutedEventArgs e)
{
string cnvsGuid = Guid.NewGuid().ToString();
System.Diagnostics.Debug.WriteLine(cnvsGuid);
tabs.Add(new CanvasTab(){label=String.Format("New Canvas {0}",countOfOpenTabs),canvasGuid=cnvsGuid});
countOfOpenTabs++;
this.tabsGrid.ItemsSource=null;
this.tabsGrid.ItemsSource=tabs;
System.Diagnostics.Debug.WriteLine(tabsGrid.Items.Count());
this.Frame.Navigate(typeof(Canvas),cnvsGuid);
}
private void tabsGrid_ItemClick(object sender, ItemClickEventArgs e)
{
this.Frame.Navigate(typeof(Canvas), ((CanvasTab)e.ClickedItem).canvasGuid);
System.Diagnostics.Debug.WriteLine(((CanvasTab)e.ClickedItem).canvasGuid);
}
private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
if (e.PageState != null)
{
this.tabs = e.PageState["tabs"] as List<CanvasTab>;
this.tabsGrid.ItemsSource = null;
this.tabsGrid.ItemsSource = tabs;
}
}
private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
{
e.PageState["tabs"] = tabs;
}
并将此代码添加到 MainPage 的构造函数中:
this.NavigationCacheMode = NavigationCacheMode.Enabled;
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += this.navigationHelper_LoadState;
this.navigationHelper.SaveState += this.navigationHelper_SaveState;
并在 Canvas.cs.xaml 中编写代码:
private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
if (e.PageState != null)
{
UIElementCollection canvasItems = e.PageState["canvasItems"] as UIElementCollection;
foreach (UIElement itm in canvasItems)
{
this.mainCanvas.Children.Add(itm);
}
this.mainCanvas.UpdateLayout();
}
}
private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
{
e.PageState["canvasItems"] = this.mainCanvas.Children;
}
并在 Canvas 的构造函数中编写这段代码:
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += this.navigationHelper_LoadState;
this.navigationHelper.SaveState += this.navigationHelper_SaveState;
this.NavigationCacheMode = NavigationCacheMode.Required;
而且它总是只为所有 Guid 缓存一个画布。
【问题讨论】:
-
你试过 this.Frame.Navigate(typeof(Canvas), myGuid) 吗?
-
WinRT 中的缓存逻辑有点奇怪,如果将缓存设置为 required 则重复使用一种类型的相同页面实例,如果禁用缓存则创建一个新实例但页面是没有缓存,看看这个问题:stackoverflow.com/questions/11539755/…
-
我重新实现了所有的缓存相关类,以便缓存机制更加灵活,请查看我的库:mytoolkit.codeplex.com/wikipage?title=Paging
-
非常感谢,我会尽快尝试
标签: c# windows-phone-8 navigation windows-phone-8.1