在 Windows Phone 8 中的页面之间传递字符串 [英] Passing a string between pages in Windows Phone 8
问题描述
我需要在 Windows Phone 8 中的两个页面之间传递一个简单的字符串.我一直在四处寻找,试图找到最好的方法 - 但我尝试过的方法却无法正常工作 - 所以我问你:在 Windows Phone 8 的两个页面之间传递一个简单字符串的最佳方法是什么.这是我用来导航到另一个页面的方法:
I need to pass a simple string between two pages in Windows Phone 8. I've been searching around, trying to find the best way of doing it - but the ones i tried turned out to not work as they should - so i ask you: What is the best way to pass a simple string between two pages in Windows Phone 8. This is the method I use to navigate to the other page:
NavigationService.Navigate(new Uri("/newpage.xaml", Urikind.Relative));
推荐答案
对于字符串变量,最容易使用查询字符串参数:
For a string variable, it's easiest to use a query string parameter:
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
为此.
Note: if your string contains only alphanumeric characters, then the above will work without modification. But, if your string might have URL-reserved characters (eg, &
, ?
), then you'll have to URL-encode them. Use the helper methods Uri.EscapeDataString
and Uri.UnescapeDataString
for this.
逃避:
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);
这篇关于在 Windows Phone 8 中的页面之间传递字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!