当我导航到包含列表视图的框架时,我的应用程序在获取数据时冻结了几秒钟。我尝试在主菜单中显示一个加载文本块,但在我的应用导航到包含列表视图的框架之前,它只是开始显示一秒钟。
有什么办法可以加快加载速度,或者在应用程序冻结之前显示加载消息?
主菜单按钮
private void moviesClicked(object sender, RoutedEventArgs e)
{
txtLoading.Visibility = Visibility.Visible;
Frame.Navigate(typeof(MovieList));
}
** listview页面的构造函数**
public sealed partial class MovieList : Page
{
private MoviesViewModel vm;
public MovieList()
{
InitializeComponent();
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
SystemNavigationManager.GetForCurrentView().BackRequested += (s, e) =>
{
// Handle the Back pressed
};
// vm contains the list loaded into the view
vm = new MoviesViewModel();
}
}
视图模型
public class MoviesViewModel
{
public ObservableCollection<MovieGeneral> movies { get; set; } = new ObservableCollection<MovieGeneral>();
private MovieService movieService = new MovieService();
public MoviesViewModel()
{
movies = movieService.LoadMovies();
}
}
答案 0 :(得分:2)
如果使用诸如HttpClient
之类的网络请求,则可以通过HttpClient.GetAsync()
方法进行异步调用,这意味着不会冻结当前的UI线程。
但是您不能在构造函数中使用await
进行异步调用,因此建议您不要将LoadMovie
方法放入MoviesViewModel
的构造函数中,而是创建一个新方法,然后在MoviesViewModel
初始化完成后进行异步调用,如下所示:
ViewModel
public class MoviesViewModel
{
...
public async Task LoadMovies()
{
movies = await movieService.LoadMovies();
}
}
页面
public sealed partial class MovieList : Page
{
private MoviesViewModel vm;
public MovieList()
{
InitializeComponent();
// other code
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
vm = new MoviesViewModel();
await vm.LoadMovies();
}
}
有关异步编程的更多信息,可以查看此document
最诚挚的问候。