win8中導航很容易,僅一行代碼就可實現,但是如果我不想讓某些頁面保存在導航堆棧中怎麼辦?微軟目前沒有提供這樣的功能。
要想實現這樣的功能需要從堆棧歷史記錄下手,從farm.GetNavigationState()這個函數找到突破口。
來看看farm.GetNavigationState()返回的信息格式:
1,3,1,37,Page1,0,39,Page2,0,34,Page3,0
第一個數字1和最後一個數字0是 固定格式,如果堆棧信息是空的,那麼堆棧的記錄就是“1,0”;
第二個數字3代表當前堆棧中頁面的個數;
第三個數字1則是當前顯示的頁面在堆棧中的索引;
第四個數字37暫時理解成頁面的ID吧;
第五個則是頁面名稱了;
所以堆棧的格式如下
1,頁面數量,當前頁面索引,頁面1ID,頁面1名稱,0,頁面2ID,頁面2名稱,...,0
瞭解堆棧格式就好辦了,開始按照我們的需求寫代碼吧。
首先我想把當前頁面信息從堆棧中刪除,代碼如下:
public static void RemoveCurrent(this Frame farm)
{
if (farm == null)
farm = Window.Current.Content as Frame;
if (farm == null) return;
string navigationHistory = farm.GetNavigationState();
List<string> history = new List<string>(navigationHistory.Split(','));
if (history.Count <= 2) return;
history.RemoveRange(history.Count - 2, 2);
int numberOfPages = int.Parse(history[1]);
int currentPageIndex = int.Parse(history[2]);
numberOfPages--;
currentPageIndex--;
history[1] = numberOfPages.ToString();
history[2] = currentPageIndex.ToString();
string newHistory = String.Join<string>(",", history.AsEnumerable());
farm.SetNavigationState(newHistory);
}
使用的時候像這樣this.Frame.RemoveCurrent();就可以了
那麼清空我要清空整個堆棧信息呢?看下面代碼:
public static void ClearAll(this Frame farm)
{
if (farm == null)
farm = Window.Current.Content as Frame;
if (farm != null)
farm.SetNavigationState("1,0");
}
調用方法同上this.Frame.ClearAll();
整個導航工具的代碼:
public static class NavigateStackUtil
{
public static void ClearAll(this Frame farm)
{
if (farm == null)
farm = Window.Current.Content as Frame;
if (farm != null)
farm.SetNavigationState("1,0");
}
public static void RemoveCurrent(this Frame farm)
{
if (farm == null)
farm = Window.Current.Content as Frame;
if (farm == null) return;
string navigationHistory = farm.GetNavigationState();
List<string> history = new List<string>(navigationHistory.Split(','));
if (history.Count <= 2) return;
history.RemoveRange(history.Count - 2, 2);
int numberOfPages = int.Parse(history[1]);
int currentPageIndex = int.Parse(history[2]);
numberOfPages--;
currentPageIndex--;
history[1] = numberOfPages.ToString();
history[2] = currentPageIndex.ToString();
string newHistory = String.Join<string>(",", history.AsEnumerable());
farm.SetNavigationState(newHistory);
}
public static void GoBack(this Frame farm)
{
if (farm == null)
farm = Window.Current.Content as Frame;
if (farm != null && farm.CanGoBack) farm.GoBack();
}
public static void GoForward(this Frame farm)
{
if (farm == null)
farm = Window.Current.Content as Frame;
if (farm != null && farm.CanGoBack) farm.GoForward();
}
public static void GoHome(this Frame farm)
{
if (farm == null)
farm = Window.Current.Content as Frame;
if (farm == null) return;
string navigationHistory = farm.GetNavigationState();
List<string> history = new List<string>(navigationHistory.Split(','));
if (history.Count <= 6) return;
history.RemoveRange(6, history.Count-6);
history[1] = "1";
history[2] = "0";
string newHistory = String.Join<string>(",", history.AsEnumerable());
farm.SetNavigationState(newHistory);
}
}
歡迎大家多多交流。