How to use SearchBox on Windows 8.1, loading results using the asynchronization method

I use SearchBox to list some items retrieved from the server. The server is called in an asynchronous method.

I get an exception. An exception of type "System.InvalidOperationException" was thrown. WinRT information: method was called at 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

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;
}}
+4
source share
2 answers

MSDN could provide very clear information about this.

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

Code to be changed 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;
}}
+4
source

. RequestDeferral Delferral Complete .

var deferral = args.Request.GetDeferral();

deferral.Complete();

, .

+3

Source: https://habr.com/ru/post/1546018/


All Articles