【问题标题】:Pass array parameters between pages在页面之间传递数组参数
【发布时间】:2013-12-19 17:56:57
【问题描述】:

我正在尝试将一个数组从 page1.xaml 传递到 page2.xaml。

int[] array = new int[] { 2,4,6,8,10,12,14,15,17,19,21,23,25,27,28,30,32,34,36,38,40,42,43,45,47,49,51,53,55,56,58,60,62,64,66,68,70,71,73,75,77,79,81,83,84,86,88,90,92,94,96,98,99 
        };
NavigationService.Navigate(new Uri("/Page2.xaml?Parameter" + array, UriKind.Relative));

如何在 page2 中获取此数组值?

【问题讨论】:

标签: c# windows-phone-7 windows-phone-8


【解决方案1】:

通过导航传递 URL 参数仅对少数情况有用:

它非常适合用于动态磁贴,或用于指示应用程序的状态等。

如果您在页面之间传递更复杂的数据,特别是如果传递该数据的页面不是导航目标 - 您绝对不应该那样传递它。

(如果您必须将其编码为 JSON,然后对其进行 urlencode,但不要这样做)。

为这样的事情使用服务或存储库模式。

我会:

  • 在其类文件中定义一个服务来管理该集合的数据。
  • App.xaml.cs 中,创建服务并使用 DI 将其传递给页面。
  • 使用更明智的持久性方式在两个页面中向服务发出请求。

【讨论】:

    【解决方案2】:
       int[] array = new int[] { 2,4,6,8,10,12,14,15,17,19,21,23,25,27,28,30,32,34,36,38,40,42,43,45,47,49,51,53,55,56,58,60,62,64,66,68,70,71,73,75,77,79,81,83,84,86,88,90,92,94,96,98,99 
                };
    you could use join function like this
    string str= string.Join("-", array.ToArray());
        NavigationService.Navigate(new Uri("/Page2.xaml?Parameter="+str, UriKind.Relative));
    
    And in destination page get this passed query string using split function like this
    
    str.Split('-');
    

    【讨论】:

      【解决方案3】:

      而不是将数组作为查询字符串传递。使用全局静态类来保存值。 并且只需在另一个位置使用该类的对象。并在任务完成时创建该类的新对象。

      【讨论】:

      • Praveen,我总是被告知这是糟糕的设计实践。
      【解决方案4】:

      你可以试试这个

      page.NavigationService.Navigate(new Uri("/Page2.xaml?Parameter="+array, UriKind.Relative));
      

      目标页面:

      string parameter = string.Empty;
      if (NavigationContext.QueryString.TryGetValue("parameter", out parameter)) {
          this.label.Text = parameter;
      }
      

      请注意,您正在创建不带“=”的 uri。请指正。

      也请检查这个问题,这里有很好的解释:

      How to pass values (parameters) between XAML pages?

      编辑:上述建议可能不适用于字符串以外的任何内容,请查看详细解决方案

      Passing a complex object to a page while navigating in a WP7 Silverlight application

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-10
        • 1970-01-01
        • 1970-01-01
        • 2014-04-22
        • 2017-12-23
        • 1970-01-01
        • 1970-01-01
        • 2017-06-24
        相关资源
        最近更新 更多