I have an AutoSuggestBox
which is set to handle the events GotFocus & TextChanged simultaneously. I have cleared the text from the text box in GotFocus event. Now the problem is that when I select any of the suggestions in AutoSuggestBox
, after selecting it calls the GotFocus event handler and clears the selected text from it.
This is the MainPage.xaml
code using the AutoSuggestBox:
<AutoSuggestBox
x:Name="auto_text_from"
HorizontalAlignment="Left"
VerticalAlignment="Center"
PlaceholderText="Enter Source"
Height="auto"
Width="280"
GotFocus="auto_text_from_GotFocus"
TextChanged="AutoSuggestBox_TextChanged"/>
And this one is the code which I have written in MainPage.xaml.cs
:
private void auto_text_from_GotFocus(object sender, RoutedEventArgs e)
{
auto_text_from.Text = "";
}
string[] PreviouslyDefinedStringArray = new string[] {"Alwar","Ajmer","Bharatpur","Bhilwara",
"Banswada","Jaipur","Jodhpur","Kota","Udaipur"};
private void AutoSuggestBox_TextChanged(AutoSuggestBox sender,AutoSuggestBoxTextChangedEventArgs args)
{
List<string> myList = new List<string>();
foreach (string myString in PreviouslyDefinedStringArray)
{
if (myString.ToLower().Contains(sender.Text.ToLower()) == true)
{
myList.Add(myString);
}
}
sender.ItemsSource = myList;
}
I want to use both of the event handlers. GotFocus
for clearing the data of Text box, and TextChanged
for showing the suggestions of writing the text in it.
Please suggest me any way to do the same.
Thanks in Advance :)
If AutoSuggestBox
has an event to handle the selection of a suggested word, like "SuggestionChosen
", a possibile solution is using a private flag managed between the various handlers.
Set a private field:
private bool _isSelectingSuggestion;
Link a method-handler like OnSuggestionChosen
to the event SuggestionChosen
and implement it like that:
private void OnSuggestionChosen(object sender, RoutedEventArgs e)
{
_isSelectingSuggestion = true;
}
Then, in GotFocus, check the flag like this:
private void auto_text_from_GotFocus(object sender, RoutedEventArgs e)
{
if (_isSelectingSuggestion)
e.Handled = true;
else
auto_text_from.Text = "";
_isSelectingSuggestion = false;
}
Obviously this works only if SuggestionChosen
is raised before GotFocus
: when GotFocus
begins, it proceeds like: "ok, I've got focus because a suggestion was chosen just a moment ago? If it's true, I must not clear my Text! Otherwise, I shall clear it!".
Let me know it this work for you!