问题
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