简体   繁体   中英

Load items asynchronously to a ListView after navigation to Page Windows Phone 8.1

I have a Windows Phone 8.1 app in which I have a button that Navigates to PageTwo.xaml . In that PageTwo.xaml.cs , in the code behind I have something like this:

string type = "";

protected override void OnNavigatedTo(NavigationEventArgs e) {
    type = e.Parameter.ToString();          
}

private void Page_Loaded(object sender, RoutedEventArgs e) {
    PageTwoListViewModel pageTwoListViewModel = ViewModelLocator.PageTwoListStatic;
    this.DataContext = pageTwoListViewModel;
}

The reason I'm setting the DataContext in the Page_Loaded event is because the project is a ClassLibrary and I have no App.xaml file, but that shouldn't affect anything related to my problem.

Then in my PageTwoViewModel I have the following:

public RelayCommand PageLoadedCommand { get; private set; }

public PageTwoListViewModel() {
    this.PageLoadedCommand = new RelayCommand(PageLoaded);
}

private void PageLoaded() {
    LoadList();
}

private async void LoadList() {
    ObservableCollection<MyListModel> _list = await DatabaseService.GetList();
    MyViewList = _list;
}

The code responsible for triggering the PageLoadedCommand is:

<Page (...)>
    <i:Interaction.Behaviors>
        <core:EventTriggerBehavior EventName="Loaded">
            <core:InvokeCommandAction Command="{Binding PageLoadedCommand}">
            </core:InvokeCommandAction>
        </core:EventTriggerBehavior>
    </i:Interaction.Behaviors>
</Page>

The problem here is that the OnNavigatedTo and both Page_Loaded events run before the Page is visible, so if I have a big list to fill, only after everything is done does it go to PageTwo.xaml , freezing the application.
What I want to do is to navigate to PageTwo.xaml and when there, fire up a loading animation and fill my ListView asynchronously. How can I do this?

As it turned out, my problem came from a rather stupid thing. My DatabaseService.GetList(); was not entirely asynchronous, and that was what was causing the problem, so the above implementation works just fine as long as you guarantee the Database calls are asynchronous.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM