同时使用GotFocus和TextChanged-Windows Phone



我有一个AutoSuggestBox,它被设置为处理事件GotFocus&同时更改文本。我已清除GotFocus事件中文本框中的文本。现在的问题是,当我在AutoSuggestBox中选择任何建议时,在选择后,它会调用GotFocus事件处理程序,并从中清除所选文本。

这是使用AutoSuggestBox:的MainPage.xaml代码

        <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"/>

这是我用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;
    }

我想同时使用这两个事件处理程序。GotFocus用于清除文本框的数据,TextChanged用于显示在其中写入文本的建议。

请给我建议同样的方法。

提前感谢:)

如果AutoSuggestBox有一个事件来处理建议单词的选择,如"SuggestionChosen",则可能的解决方案是使用在各个处理程序之间管理的私有标志。

设置专用字段:

private bool _isSelectingSuggestion;

将类似OnSuggestionChosen的方法处理程序链接到事件SuggestionChosen,并像这样实现它:

private void OnSuggestionChosen(object sender, RoutedEventArgs e)
{
    _isSelectingSuggestion = true;
}

然后,在GotFocus中,检查如下标志:

private void auto_text_from_GotFocus(object sender, RoutedEventArgs e)
{
    if (_isSelectingSuggestion)
        e.Handled = true;
    else
        auto_text_from.Text = "";
   _isSelectingSuggestion = false;
}

显然,只有当SuggestionChosenGotFocus之前引发时,这才有效:当GotFocus开始时,它会像这样进行:"好吧,我有焦点了,因为刚才刚刚选择了一个建议?如果是真的,我不能清除我的文本!否则,我会清除它!"。

让我知道这是为你做的!

@MK87:是的,它只做了一点更改!!:)

    private bool _isSelectingSuggestion;
    private void OnSuggestionChosen(AutoSuggestBox sender, AutoSuggestBoxSuggestionChosenEventArgs args)
    {
        _isSelectingSuggestion = true;
    }
    private void auto_text_from_GotFocus(object sender, RoutedEventArgs e)
    {
        if (!_isSelectingSuggestion)
            auto_text_from.Text = "";
        _isSelectingSuggestion = false;
    }

我不得不删除这行:

e.Handled == true;

因为它给我的错误是CCD_ 14。

感谢您的帮助:):)

相关内容

  • 没有找到相关文章

最新更新