How do I pass a variable to another Silverlight page?
I have an OnClick event for my Pushpins as below.
void BusStop1061_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("Buses from this station: City Link");
}
I would like to pass the bustop number to another page and to the int "PassedVariable"
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
string site = "http://www.sourceDomain?stop=" + PassedVariable;
webBrowser1.Navigate(new Uri(site, UriKind.Absolute));
}
I was thinking of creating a constant int on the Page one, then passing it to page开发者_开发问答 2 using urimapping, but it doesn't seem to work and I figured someone might have a better option
I have had a look at similar posts, but they dont quite answer my question.
There are multiple ways to achieve this.
One way, is to create a BustopNumber property in the App.xaml.cs class, a set it in one page, and access it else where.
This is my preferred approach, although you have to guard against the case where the value isn't set or invalid.
Another approach is to pass it in as a query string parameter, similar to what you are doing in your code snippet above. In the navigated to page, you can access the query string parameter via the NavigationContext
object and look for by name.
Edit to add:
public partial class App : Application
{
public static int BusStopNumber { get; set;}
}
//And in your application you can access it like so:
App.BusStopNumber = 10;
Obviously there are issues with encapsulation, as this is essentially a hack for global, but if used carefully, can offer a quick and easy way to share information across multiple pages.
One of the approaches is to add a class with common data that can be shared between the views. This is one of the way and may not be the best.
You can have a static class which can create singleton of Session and provide it to XAML as part of User control binding. Session class can be enhanced in future with multiple properties if you want.
View1 View2
^ ^
| |
| |
v v
Session Service (stores user selection)
View1 and View2 should have reference to Session Service.
public class Session
{
public int BusStop {get; set;}
}
You should start looking at MVVM pattern to modularize your code and avoid any such issues in future.
you can use PhoneApplicationService. include the shell namespace. using Microsoft.Phone.Shell;
PhoneApplicationService appSer = PhoneApplicationService.Current;
appSer["busStopNumber"]=number;
and when you want to use it already in another page, do this (initialize the appSer also in the page)
if(appSer["busStopNumber"]!=null)
{
int number = (int)appSer["busStopNumber"];
}
精彩评论