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

独自空忆成欢 提交于 2019-12-06 04:06:09

问题


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;
}}

回答1:


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;
}}



回答2:


You must use deferral. You must add RequestDeferral and Deferral Complete before and your append suggestion respectively.

Before you append

var deferral = args.Request.GetDeferral();

After you append

deferral.Complete();

Hope it helps.



来源:https://stackoverflow.com/questions/24413748/how-to-use-searchbox-in-windows-8-1-by-loading-the-results-using-a-async-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!