Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SearchBox in Windows 8.1 by loading the results using a async method

I am using a SearchBox to list some items that are obtained from the server. The call to the server is happening in a async method.

I am getting an exception An exception of type 'System.InvalidOperationException' occurred WinRT information: A method was called at an unexpected time.

My XAML

<SearchBox Name="SearchBox"
    Style="{StaticResource AccountSearchBoxStyle}"
    Grid.Row="1"
    Margin="120,0,0,0"
    HorizontalAlignment="Left"
    SuggestionsRequested="SearchBox_SuggestionsRequested"
    SearchHistoryEnabled="False" > </SearchBox>

My code behind

private async void SearchBox_SuggestionsRequested(SearchBox sender,
SearchBoxSuggestionsRequestedEventArgs args){
if (string.IsNullOrEmpty(args.QueryText))
{
    return;
}
var collection = args.Request.SearchSuggestionCollection;
if(oldquery != args.QueryText)
{
    var listOfBanks = await addFIPageViewModel.GetBanksOnQuery();
    foreach (Institution insti in listOfBanks)
    {
        collection.AppendQuerySuggestion(insti.name);
    }
    oldquery = args.QueryText;
}}
like image 862
HelpMatters Avatar asked Mar 20 '23 05:03

HelpMatters


1 Answers

MSDN could have provided much clear information about this.

After spending time I stumbled upon this blog and found the answer

The code behind needs to be modified as follows.

private async void SearchBox_SuggestionsRequested(SearchBox sender,
SearchBoxSuggestionsRequestedEventArgs args){
if (string.IsNullOrEmpty(args.QueryText))
{
    return;
}
var collection = args.Request.SearchSuggestionCollection;
if(oldquery != args.QueryText)
{
    //ADD THIS LINE
    var deferral = args.Request.GetDeferral();

    var listOfBanks = await addFIPageViewModel.GetBanksOnQuery();
    foreach (Institution insti in listOfBanks)
    {
        collection.AppendQuerySuggestion(insti.name);
    }

    //ADD THIS LINE
    deferral.Complete();

    oldquery = args.QueryText;
}}
like image 175
HelpMatters Avatar answered Apr 09 '23 16:04

HelpMatters