【发布时间】:2016-11-16 20:12:58
【问题描述】:
所以我有一个带有 XAML 页面的 Windows 10 应用程序,该页面具有 Pivot 项,Pivot 的默认行为是,每当您导航到带有 Pivot 的页面时,@ 上的第一项987654324@ 立即被选中。我想要做的是在Pivot 运行的第一项之前执行一些代码。
上下文中的代码
public sealed partial class ContentFrame : Page
{
private IMobileServiceTable<News> NewsItems = App.MobileService.GetTable<News>();
private List<News> AllNews;
private List<News> Windows = new List<News>();
private List<News> Apple = new List<News>();
private List<News> Google = new List<News>();
private List<News> Other = new List<News>();
private List<News> Top = new List<News>();
private string WeekID;
public ContentFrame()
{
this.InitializeComponent();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
WeekID = e.Parameter as string;
AllNews = await NewsItems.Where(News => News.Week == WeekID).ToListAsync();
separateContent();
}
private void separateContent()
{
foreach (News item in AllNews)
{
Debug.WriteLine(item.Tag);
if (item.Tag == "Windows")
Windows.Add(item);
else if (item.Tag == "Apple")
Apple.Add(item);
else if (item.Tag == "Google")
Google.Add(item);
else if (item.Tag == "Other")
Other.Add(item);
else
Top.Add(item);
}
}
private void Tags_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
IntroHead.FontWeight = FontWeights.Normal;
WindowsHead.FontWeight = FontWeights.Normal;
AppleHead.FontWeight = FontWeights.Normal;
GoogleHead.FontWeight = FontWeights.Normal;
OtherHead.FontWeight = FontWeights.Normal;
switch (Tags.SelectedIndex)
{
case 0:
IntroHead.FontWeight = FontWeights.SemiBold;
StoryContent.Navigate(typeof(TopNewsPage), Top);
break;
case 1:
WindowsHead.FontWeight = FontWeights.SemiBold;
StoryContent.Navigate(typeof(OtherNews), Windows);
break;
case 2:
AppleHead.FontWeight = FontWeights.SemiBold;
StoryContent.Navigate(typeof(OtherNews), Apple);
break;
case 3:
GoogleHead.FontWeight = FontWeights.SemiBold;
StoryContent.Navigate(typeof(OtherNews), Google);
break;
case 4:
OtherHead.FontWeight = FontWeights.SemiBold;
StoryContent.Navigate(typeof(OtherNews), Other);
break;
}
}
}
与问题相关的代码行:
StoryContent.Navigate(typeof(TopNewsPage), Top);
这执行得太快了,我想等到separateContent(); 方法完成之前我允许应用在我的 XAML 布局上导航 Pivot 控件。如果我不这样做,传入的参数 (Top) 将是 null/空,一旦我导航到 TopNewsPage,我的应用程序就会抛出异常。
我该怎么做?
我知道我制作我的应用程序的方式并不是最好的(MVVM 是我希望在未来探索的东西)但这是我的第一个应用程序,我真的只是想让它工作。我对Task 进行了一些探索,但似乎没有任何帮助,因为Pivot 导航太快了。
【问题讨论】:
-
为什么不在
InitializeComponent()之后调用separateContent();? -
好问题。在调用
separateContent();之前,我需要在OnNavigatedTo方法的参数中传递WeekID,所以它不适用于我的情况。