how to bind AutoCompleteBox to a non-static List in windows phone
i am working with the AutoCompleteBox from the WP7 Silverlight Toolkit. i have seen examples where they bind a static list (non-changing List) of strings to the AutoCompleteBox. however, is there an example showing how to bind the AutoCompleteBox in a more dynamic way? my attempt below keeps throwing an InvalidOperationException: Cannot change ObservableCollection during a CollectionChanged or PropertyChanged event.
this is what i have in my xaml.
<toolkit:AutoCompleteBox x:Name="tbQuery" TextChanged="tbQuery_TextChanged" />
in my code-behind, i have simulated going to a database or across the web as follows.
private void tbQuery_TextChanged(object sender, RoutedEventArgs e)
{
AutoCompleteBox acBox = sender as AutoCompleteBox;
string txt = acBox.Text;
if (txt.Length > 0)
{
/开发者_如何学C/exception thrown below here;
//_words is of type ObservableCollection<string>
//earlier, acBox.ItemsSource was set to _words
_words.Clear();
_words.Add(txt + "a");
_words.Add(txt + "b");
_words.Add(txt + "c");
}
}
i also tried something like what is below too, but it didn't work as well. the same InvalidOperationException is thrown.
private void tbQuery_TextChanged(object sender, RoutedEventArgs e)
{
AutoCompleteBox acBox = sender as AutoCompleteBox;
string txt = acBox.Text;
if (txt.Length > 0)
{
List<string> list = new List<string>();
list.Add(txt + "a");
list.Add(txt + "b");
list.Add(txt + "c");
//exception thrown below here;
acBox.ItemsSource = list;
}
}
the demo in the toolkit only shows using a static resource, and most examples only show with a static list. is this because AutoCompleteBox is not to be used in a dynamic way?
Exactly what is the point of changing the list on the fly? The autocompletion box filters automatically your list from the given itemssource.
Anyway, the TextChanged is first called after the AutoCompleteBox have attempted to filter out your items. If you press the back button after having typed in a few characters, you will see your generated items suggested.
You could most likely reprogram the AutoCompleteBox to your functionality (it's open source), but I think it would be better if you explained your purpose, so we can advice better.
Well you don't actually need to reprogram the AutoCompleteBox. You can handle the Populating event to link the AutoCompleteBox to dynamically generated data.
This is what you are looking for. It's a good article with a good example. And as mention don't forget to call PopulateComplete() when the manual population operation is complete.
You can also set the ItemFilter property to a custom Filter for defining your own search logic. See this for details. Remember to set the FilterMode to Custom.
精彩评论