如何将变量传递给另一个Silverlight页面?

时间:2011-09-15 05:05:16

标签: c# silverlight windows-phone-7

我的Pushpins有一个OnClick事件,如下所示。

void BusStop1061_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    MessageBox.Show("Buses from this station: City Link");
}

我想将bustop号码传递给另一个页面并传递到int“PassedVariable”

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
    string site = "http://www.sourceDomain?stop=" + PassedVariable;
    webBrowser1.Navigate(new Uri(site, UriKind.Absolute));

}

我正在考虑在Page 1上创建一个常量int,然后使用urimapping将其传递给第2页,但它似乎不起作用,我认为有人可能有更好的选择

我看过类似的帖子,但他们并没有完全回答我的问题。

3 个答案:

答案 0 :(得分:1)

有多种方法可以实现这一目标。

一种方法是在App.xaml.cs类中创建一个BustopNumber属性,在一个页面中设置它,然后在其他位置访问它。

这是我的首选方法,但您必须防止未设置或无效的情况。

另一种方法是将其作为查询字符串参数传递,类似于您在上面的代码段中所做的操作。在导航到页面中,您可以通过NavigationContext对象访问查询字符串参数并按名称查找。

编辑添加:

public partial class App : Application
{
    public static int BusStopNumber { get; set;}
}

//And in your application you can access it like so:
App.BusStopNumber = 10;

显然封装存在问题,因为这本质上是对全局的破解,但如果仔细使用,可以提供一种快速简便的方法来跨多个页面共享信息。

答案 1 :(得分:1)

其中一种方法是添加一个具有可在视图之间共享的公共数据的类。这是其中一种方式,可能不是最好的方式。

您可以拥有一个静态类,它可以创建Session的单例并将其作为用户控件绑定的一部分提供给XAML。如果您愿意,将来可以使用多个属性增强会话类。

    View1    View2
     ^         ^
     |         |
     |         |
     v         v
   Session Service (stores user selection)

View1和View2应该引用会话服务。

public class Session
{
  public int BusStop {get; set;}
}

您应该开始考虑MVVM模式来模块化您的代码并避免将来出现任何此类问题。

答案 2 :(得分:0)

您可以使用PhoneApplicationService。包括shell命名空间。 using Microsoft.Phone.Shell;

PhoneApplicationService appSer = PhoneApplicationService.Current;
appSer["busStopNumber"]=number;

如果您想在另一个页面中使用它,请执行此操作(在页面中初始化appSer)

if(appSer["busStopNumber"]!=null)
{ 
int number = (int)appSer["busStopNumber"];
}
相关问题