萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Windows Phone 頁面導航傳值:Query String 參數傳遞完整範例

導航傳值的兩大核心問題

  1. 來源頁面如何將資料附加在導航 URI 上?
  2. 目標頁面如何解析並取得這些參數?

方案:URI Query String + NavigationContext

Silverlight 導航框架支援在 URI 後附加查詢字串,目標頁面透過 NavigationContext.QueryString 字典取值。

完整代碼實作

1. 來源頁面:構建帶參數的 URI

private void txt1_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
{
    string destination = "/Page1.xaml";

    // 假設要傳遞背景顏色的 RGB 值
    if (ContentPanel.Background is SolidColorBrush brush)
    {
        Color clr = brush.Color;
        destination += String.Format("?Red={0}&Green={1}&Blue={2}", clr.R, clr.G, clr.B);
    }

    // 執行導航
    NavigationService.Navigate(new Uri(destination, UriKind.Relative));
}

2. 目標頁面:解析 QueryString

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    // 從 QueryString 取值(全部為 string 型別)
    if (NavigationContext.QueryString.TryGetValue("Red", out string rStr) &&
        NavigationContext.QueryString.TryGetValue("Green", out string gStr) &&
        NavigationContext.QueryString.TryGetValue("Blue", out string bStr))
    {
        if (byte.TryParse(rStr, out byte r) &&
            byte.TryParse(gStr, out byte g) &&
            byte.TryParse(bStr, out byte b))
        {
            ContentPanel.Background = new SolidColorBrush(Color.FromArgb(255, r, g, b));
        }
    }
}

關鍵細節

  • UriKind.Relative:相對 URI,適用於專案內頁面導航。
  • 參數編碼: 值若含特殊字元(空格、&、=)需 Uri.EscapeDataString() 編碼。
  • 型別轉換: QueryString 僅存字串,取用時需自行 TryParse 轉換。
  • 導航歷程: 使用者按「返回鍵」會回到來源頁面,資料不會自動回傳(若需雙向請用共享狀態或事件)。

適用場景 vs 替代方案

場景推薦方式
簡單、少量、一次性參數(ID、Token、顏色)Query String(本文方案)
複雜物件、大量資料、雙向綁定App 共享屬性 / 靜態 ViewModel / 暫存檔
頁面間解耦、多對多通訊事件聚合器 / Messenger (MVVM Light)

結語

Query String 是 WP 頁面導航傳值最原生、輕量的方式,適合「帶參數跳轉」的典型場景。掌握 NavigationService.Navigate 與 NavigationContext.QueryString 的配合,即可輕鬆實現頁面間的資料流動。

copyright © 萬盛學電腦網 all rights reserved