I am trying to figure out how the best way to use AutoCompleteBox with MVVM Light.
public ICommand AutoComplete
{
get
{
return new RelayCommand<KeyEventArgs>(e =>
{
var txtBox = e.OriginalSource as TextBox;
if (e.Key == Key.Unknown)
{
return;
}
string autoComplete = txtBox.Text + e.Key;
if (autoComplete.Length >= 3)
{
RestClient c = new RestClient("http://localhost:3333/api/store");
RestRequest r = new RestRequest("/GetStoreNames",Method.GET);
r.AddParameter("Name", autoComplete);
r.AddParameter("Latitude", "49");
r.AddParameter("Longitude", "49");
var d = c.BuildUri(r);
c.ExecuteAsync(r, response2 =>
{
var content = response2.Content;
});
}
});
}
}
<i:Interaction.Triggers>
<i:EventTrigger EventName="KeyUp">
<GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding AutoComplete, Mode=OneWay}" PassEventArgsToCommand="True"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<toolkit:AutoCompleteBox x:Name="acbStore" Margin="154,196,29,0" VerticalAlignment="Top" RenderTransformOrigin="0.6,0.083" Height="162" MinimumPopulateDelay="500"/>
I did the above but there is a couple problems.
Once I get the results back how do I show them in the auto complete area?
How can I delay it from doing to many requests at once? As you can see I don't want to hit the server before 3 characters are entered but after that it is fair game. I am kinda worried that like 20 requests will be done to the server before the 1st request makes it back leading to wasted bandwidth.
I am assuming you are using KeyDown
event or similar? That is not the way you want to do it. Instead, bind the AutoCompleteBox
Populating
event and set the MinimumPrefixLength
on your AutoCompleteBox
to 3 so thatPopulating
is fired only when you have 3+ characters. To show the list retrieved in your control, the list need to be bound to ItemsSource
property then a method needs to be called, PopulateComeplte()
.
You can see my answer here on a similar Question.
However, it is not MVVM friendly since you need to call a method on your AutoCompleteBox
to trigger the control to show the list from your webservice. Take a look at this article for a MVVM-friendly approach, scroll down to "Bonus: MVVM-friendly asynchronous filtering" section.