![](/img/trans.png)
[英]How to access element of MainPage.xaml into another page in uwp application?
[英]How to send a list of object from my MainPage.xaml to another page
導航到另一頁時,如何使對象列表可用於另一頁。
例如在我的mainpage.xaml中
var data2 = from query in document.Descendants("weather")
select new Forecast
{
date = (string)query.Element("date"),
tempMaxC = (string)query.Element("tempMaxC"),
tempMinC = (string)query.Element("tempMinC"),
weatherIconUrl = (string)query.Element("weatherIconUrl"),
};
forecasts = data2.ToList<Forecast>();
....
NavigationService.Navigate(new Uri("/WeatherInfoPage.xaml", UriKind.Relative));
然后在另一堂課中,我想讓它可用,以便我可以像這樣使用它
private void AddPageItem(List<Forecast> forecasts)
{
..
}
這可能對您有幫助
//使用PhoneApplicationService.Current.State存儲列表//
PhoneApplicationService.Current.State [“ yourparam”] = lstpro.SelectedItems; NavigationService.Navigate(新Uri(“ / res.xaml”,UriKind.Relative))
在第二頁
私有IList iList1;
//在onNavigatedTo事件中,將存儲的列表分配給變量//
受保護的重寫void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
var i= PhoneApplicationService.Current.State["yourparam"];
//convert object to list//
iList1 = (IList) i ;
lstpro.ItemsSource = iList1;
}
您可以使用放置在App.xaml.cs中的全局變量:
//In App.xaml.cs
public static List<Forecast> SelectedForecasts = null;
該變量將在整個應用程序中可用。
通常,我使用通過Singleton模式實現的其他類。 在該類中,我存儲需要在頁面之間交換的所有數據。 基本上,它與Jon提到的方法相同,但是我希望保持App.xaml.cs的干凈。 因此,您可以從應用程序中的任何位置訪問數據。
有幾種方法可以做到這一點,但沒有一個是真正的優雅。 主要問題是處理邏輯刪除場景:要完全還原,即使應用程序剛剛被重新激活,頁面也必須能夠檢索其輸入列表(並且刪除了先前導航中的所有先前狀態...)
要導航到下一頁:
NavigationService.Navigate(new Uri("/WeatherInfoPage.xaml?data1;data2;serializeddata", UriKind.Relative));
要在下一頁中檢索數據,您必須從當前Uri中進行解析並反序列化:
Uri currentUri = ((App)Application.Current).RootFrame.CurrentSource;
您還可以將列表存儲到位於AppSettings或PhoneApplicationService.Current.State中的專用變量中,然后在新頁面中進行導航和檢索。 Perharps創建一個專門的班級來完成這項工作可能很有趣。 它可以是推送和檢索參數,確保參數唯一性,管理參數生命周期等的集中場所。它也可以應用於第一個建議。
最后,如果您的列表保存在某個位置(文件,嵌入式數據庫),則只需將ID傳遞到下一頁(使用以前的建議),然后通過從保存的源中查詢來檢索相應的列表即可。
在這兩種情況下,您都可以將列表傳遞到下一頁並處理邏輯刪除場景。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.