【发布时间】:2018-06-26 17:49:00
【问题描述】:
我的设置基本如下:
-
NavigationView的MenuItemsSource绑定到viewModel.NavItems。-
NavItems是viewModel的计算属性。
-
视图模型类实现
INotifyPropertyChanged用于绑定目的-
视图模型的
Books被异步加载。
什么有效
到达页面后会显示NavigationViewItems。
问题
我需要将指定的NavigationViewItem 设置为NavigationView 的SelectedItem。但是NavigationViewItem(来自viewModel)不能在OnNavigatedTo(NavigationEventArgs e) 中使用,因为此时viewModel.NavItems 还没有准备好。
那么在这种异步情况下是否有选择NavigationViewItem 的模式?
XAML
<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;
}
…
}
【问题讨论】:
标签: c# asynchronous data-binding uwp windows-10