2011-09-15 152 views
0

我有一个我的Pushpins的OnClick事件如下。如何将变量传递给另一个Silverlight页面?

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)); 

} 

我想在第一页上创建的整型,然后将它传递到页面2使用urimapping,但它似乎并没有工作,我想有人可能有更好的选择

我曾看过类似的帖子,但他们不完全回答我的问题。

+0

可能重复[调用从另一种形式的C#变量(HTTP ://stackoverflow.com/questions/5928071/call-variable-from-another-form-c) –

+0

也http://stackoverflow.com/questions/5865588/how-to-pass-value-from-textbox-to -label-on-different-form和http://stackoverflow.com/questions/4247807/passing-variable-between-winforms –

+0

和http:// stackoverflow。com/questions/7316965/data-sharing-multiple-viewmodels/7338294#7338294 –

回答

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; 

显然有与封装问题,因为这本质上是全球性黑客攻击,但如果小心使用,可以提供一种快速简便的方式来分享在多个页面信息。

+0

App.Xaml的方式听起来很有趣。我不熟悉这一点。任何代码示例的更改可以帮助我解决问题? – Rhys

+0

谢谢,我使用了导航方法,效果很好。谢谢 – Rhys

+0

Rhys,更新了显示如何将值添加到App.xaml.cs的答案 – Alan

1

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

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

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

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

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

您应该着眼于MVVM模式来模块化您的代码,并在将来避免任何此类问题。

+0

谢谢我刚刚阅读了关于Model View View Model的内容,但我现在仍然在学习如此之外的一点点。 – Rhys

0

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

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

,当你想在另一个页面已经在使用它,这样做(初始化appSer也在页)

if(appSer["busStopNumber"]!=null) 
{ 
int number = (int)appSer["busStopNumber"]; 
} 
+0

这似乎并不奏效'appSer [“busStopNumber”] = number;'不能使用[]表达式应用索引。是对的吗? – Rhys

相关问题