[英]Passing a string between pages in Windows Phone 8
我需要在Windows Phone 8中的兩個頁面之間傳遞一個簡單的字符串。我一直在搜索,試圖找到最好的方法 - 但我試過的那些結果不能正常工作 - 所以我問你:在Windows Phone 8中在兩個頁面之間傳遞簡單字符串的最佳方法是什么。這是我用於導航到另一個頁面的方法:
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.EscapeDataString
和Uri.UnescapeDataString
。
逃離:
string encodedValue = Uri.EscapeDataString("R&R");
NavigationService.Navigate(new Uri("/newpage.xaml?key=" + encodedValue, Urikind.Relative));
為了unescape:
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)。 你想將字符串從homepage.xaml傳遞到newpage.xaml,然后在homepage.xaml中發送這樣的消息
Messenger.Default.Send(new PageMessage{message="Hello World"});
在newpage.xaml中,你應該像這樣注冊信使,
Messenger.Default.Register<PageMessage>(this, (action) => ReceiveMessage(action));
private object ReceiveMessage(PageMessage action)
{
string receivedMessage=action.message;
return null;
}
像這樣你甚至可以在MVVM架構中傳遞任何導航。
HY,
另一種解決方案是根據您的需要創建一個具有一個或多個string類型屬性的靜態類,它可以增強您需要的方式。
看看Caliburn.micro。 設置非常簡單,並允許您以強類型方式通過視圖傳遞參數,如下所示:
public void GotoPageTwo() {
navigationService.UriFor<PivotPageViewModel>()
.WithParam(x => x.NumberOfTabs, 5)
.Navigate();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.