问题描述
我的设置基本上如下:
-
NavigationView
的MenuItemsSource
已绑定到viewModel.NavItems
.
-
NavItems
是viewModel
的计算属性.
NavItems
is a computed property ofviewModel
.
视图模型类出于绑定目的实现 INotifyPropertyChanged
The view model class implements INotifyPropertyChanged
for binding purpose
到达页面后,会显示 NavigationViewItem
.
我需要将指定的 NavigationViewItem
设置为 NavigationView
的 SelectedItem
.但是,没有 NavigationViewItem
(来自 viewModel
)可以在 OnNavigatedTo(NavigationEventArgs e)
,因为在该点.还没准备好.
I need to set a specified NavigationViewItem
as the SelectedItem
of the NavigationView
. But there's no NavigationViewItem
(from viewModel
) to use inside OnNavigatedTo(NavigationEventArgs e)
, because at that point viewModel.NavItems
is not ready yet.
那么在这种异步情况下,是否有一种选择 NavigationViewItem
的模式?
So is there a pattern for selecting a NavigationViewItem
in this async situation?
<NavigationView x:Name="navView"
MenuItemsSource="{x:Bind viewModel.NavItems, Mode=OneWay}"
SelectionChanged="NavView_SelectionChanged" >
…
视图模型
internal class MainPageViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
// The data service
private MainDataService mainDataService = new MainDataService();
private List<Book> books = new List<Book>();
public List<Book> Books
{
get
{
return this.books;
}
set
{
this.books = value;
this.OnPropertyChanged();
this.OnPropertyChanged("NavItems");
}
}
public IEnumerable<NavigationViewItemBase> NavItems
{
get
{
return Books.SelectMany(
b => (new List<NavigationViewItemBase> { new NavigationViewItemHeader {
Content = b.Title,
Tag = b.Title
} })
.Concat(
b.Sections.Select(s => new NavigationViewItem
{
Content = s.Title,
Icon = new FontIcon { Glyph = "\uE8B7", FontFamily = new FontFamily("Segoe MDL2 Assets") }
})
)
);
}
}
// @param selectedBookIndex: the index of the book whose first section
// should be selected.
public async Task UpdateBooks(int selectedBookIndex)
{
await mainDataService.PrepareData();
this.Books = mainDataService.Books;
}
…
}
推荐答案
对于异步情况,您需要使用 ObservableCollection
而不是 List
.它代表了一个动态数据收集,当添加,删除或刷新整个列表时会提供通知.
For async situation, you need use ObservableCollection
but not List
. And it represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.
在数据未准备好之前,您可以将 Frame
导航保留到 NavigationView
Loaded事件中用作放置器的默认页面.有关更多信息,请参考数据绑定深度.
Before the data is not ready, you could keep the Frame
navigation to the default page that used as placehoder within NavigationView
Loaded event.For more you could refer Data binding in depth.
这篇关于绑定更新后,如何以编程方式选择"NavigationView"的绑定"NavigationViewItem"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!