在WP7開發中,經常需要在不同的頁面切換,是以也會經常遇到資料在不同頁面之間的傳遞問題,下面介紹幾種資料傳遞的方法
1、頁面之間傳遞資料(字元串)
通過頁面導航的Uri位址進行傳遞,導航到 Page2.xaml 頁面
string uriString = "/page2.xaml?parameter1=value1¶meter2=value2";
Uri uri = new Uri(uriString, UriKind.Relative);
this.NavigationService.Navigate(uri);
字元串參數接在頁面位址後面,格式為: ?參數名1=參數值1&參數名2=參數值2
在目标頁面的 OnNavigatedTo() 函數中接受參數
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (this.NavigationContext.QueryString.Count > 0)
{
string value1, value2;
this.NavigationContext.QueryString.TryGetValue("parameter1", out value1);
this.NavigationContext.QueryString.TryGetValue("parameter1", out value2);
}
base.OnNavigatedTo(e);
}
2、頁面之間傳遞對象
一般的,我們不能在頁面之間傳遞對象,頁面之間對象傳遞通常采用全局對象來做,由于全局對象所有頁面共享,是以也可以實作資料傳遞的功能
- 定義全局對象
在App.xaml.cs檔案中的 App類 的構造函數前面添加靜态屬性 GlobalValue
public partial class App : Application
{
public static String GlobalValue { get; set; }
}
然後頁面之間通過 App.GlobalValue 引用并對其進行操作
3、關于别名的使用
關于别名的使用(用的比較少),當應用程式的Uri位址導航比較多的時候,為了友善管理,我們可以通過别名的方式來通路
别名的使用也是通過定義全局資源來實作的
在App.xaml檔案中添加命名空間
xmlns:nav="clr-namespace:System.Windows.Navigation;assembly=Microsoft.Phone"
然後添加資源:
<Application.Resources>
<nav:UriMapper x:Key="UriMapper">
<nav:UriMapping Uri="Music" MappedUri="/Music.xaml"/>
<nav:UriMapping Uri="Music/{song}" MappedUri="/Music.xaml?SongName={song}"/>
<nav:UriMapping Uri="Music&{song}&{author}" MappedUri="/Music.xaml?SongName={song}&SongAuthor={author}" />
</nav:UriMapper>
</Application.Resources>
第一種為無參數别名導航
第二種為帶參數單個參數導航,{}裡面的名字要完全一樣
第三種為多參數導航,參數與參數之間用 & 連接配接(實際上就是&符号),注意:參數與别名之間也用 & 連接配接,使用與第二種有點不同
下面是使用:
在xaml中使用
在App.xaml.cs檔案中的App類的構造函數中添加導航映射到 RootFrame 的 UriMapper
this.RootFrame.UriMapper = Resources["UriMapper"] as UriMapper;
然後就可以再Xaml檔案中使用UriMapper資源了
<HyperlinkButton Content="音樂1" Height="30" HorizontalAlignment="Left" Margin="68,40,0,0" Name="MusicshyperlinkButton1" VerticalAlignment="Top" Width="200" NavigateUri="Music" />
<HyperlinkButton Content="音樂2" Height="30" HorizontalAlignment="Left" Margin="68,65,0,0" Name="MusicshyperlinkButton2" VerticalAlignment="Top" Width="200" NavigateUri="Music/借口" />
<HyperlinkButton Content="音樂3" Height="30" HorizontalAlignment="Left" Margin="68,100,0,0" Name="MusicshyperlinkButton3" VerticalAlignment="Top" Width="200" NavigateUri="Musics&借口&周傑倫" />
在C#代碼中使用
在C#代碼中很少使用UriMapper,可以通過資源的方式通路,但是好像不能通過key來索引,隻能通過index索引
UriMapper uriMapper = App.Current.Resources["UriMapper"] as UriMapper;
Uri uri = uriMapper.UriMappings[0].MappedUri;