NavigationService.Navigate(new Uri("/newpage.xaml", Urikind.Relative));
NavigationService.Navigate(new Uri("/newpage.xaml", Urikind.Relative));
对于一个字符串变量,最简单的方法是使用查询字符串参数:
NavigationService.Navigate(new Uri("/newpage.xaml?key=value", Urikind.Relative));
使用NavigationContext.QueryString
在目标页面上获取它:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (NavigationContext.QueryString.ContainsKey("key"))
{
string val = NavigationContext.QueryString["key"];
// etc ...
}
}
注意: 如果你的字符串只包含字母数字字符,那么上面的代码将可以直接使用。但是,如果你的字符串可能包含URL保留字符(例如:&
,?
),则必须对它们进行URL编码。使用辅助方法Uri.EscapeDataString
和Uri.UnescapeDataString
进行转换。
要进行转义:
string encodedValue = Uri.EscapeDataString("R&R");
NavigationService.Navigate(new Uri("/newpage.xaml?key=" + encodedValue, Urikind.Relative));
取消转义:
string encodedValue = NavigationContext.QueryString["key"];
string val = Uri.UnescapeDataString(encodedValue);
我必须说,对于简单的数据,@McGarnagle可能是更好的解决方案。
话虽如此,这也是一种极快且肮脏的方法。该方法还可以处理复杂对象。
我喜欢使用PhoneApplicationService.State
,它是一个Dictionary<String,Object>
。
PhoneApplicationService.State.add("KeyName",YourObject);
var yourObject = PhoneApplicationService.State["KeyName"];
如果你正在使用MVVM架构,则可以在注册后使用Messenger传递字符串。 创建一个模型类(比如PageMessage),其中包含一个字符串变量(比如message)。 如果你想要从homepage.xaml传递字符串到newpage.xaml,在homepage.xaml中只需像这样发送消息:
Messenger.Default.Send(new PageMessage{message="Hello World"});
Messenger.Default.Register<PageMessage>(this, (action) => ReceiveMessage(action));
private object ReceiveMessage(PageMessage action)
{
string receivedMessage=action.message;
return null;
}
就像这样,你甚至可以在MVVM架构中传递任何东西,包括导航。
你好,
另一种解决方案是创建一个静态类,其中包含一个或多个字符串类型的属性,具体取决于你需要什么,这样可以增强在需要时可用的方式。
看看Caliburn.micro吧。它非常简单易用,可以让你以强类型的方式通过视图传递参数,就像这样:
public void GotoPageTwo() {
navigationService.UriFor<PivotPageViewModel>()
.WithParam(x => x.NumberOfTabs, 5)
.Navigate();
}