【问题标题】:AutoCompleteBox with TextChanged event not selecting properly带有 TextChanged 事件的 AutoCompleteBox 未正确选择
【发布时间】:2011-10-07 22:41:22
【问题描述】:

您好,我正在使用这样的 AutoCompleteBox

<!-- XAML Code -->
<sdk:AutoCompleteBox Grid.Row="2"
         FilterMode="None"
         ItemsSource="{Binding Customers}"
         SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}"
         Text="{Binding CustomerSearchString, Mode=TwoWay}"
         ValueMemberBinding="{Binding Path=FullName}"
         ValueMemberPath="FullName"
         TextChanged="{ext:Invoke MethodName=Search, Source={Binding}}"/>

C#部分:

// Search Method in the viewmodel
public void Search()
{
    var customerOperation = _context.Load(_context.GetCustomerByNameQuery(CustomerSearchString));
    customerOperation.Completed += (s, e) => Customers = new List<Customer>(customerOperation.Entities);
}

在我的应用程序中快速搜索客户以获得快速且简单的搜索方法。我让它在下拉列表中正确显示所有内容,当我用鼠标选择它时,它工作得很好。

但是当我按下 ArrowDown 时,您会看到文本出现一瞬间,但随后它恢复并将光标放回文本框中,而不是选择第一个条目。我尝试使用 TextInput 事件,但不会触发。

如何避免这种行为?

解决方案:

问题是,当用户选择一个条目时,TextChanged 事件被触发,从而创建了某种竞争条件,例如 Text 被重置的行为。 解决方案是使用 KeyUp 事件(不要使用 KeyDown,因为 Text 属性还不会更新)。当用户选择某些东西时不会触发此事件,从而解决问题。

最终代码(ViewModel 不变):

<!-- XAML Code -->
<sdk:AutoCompleteBox Grid.Row="2"
         FilterMode="None"
         ItemsSource="{Binding Customers}"
         SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}"
         Text="{Binding CustomerSearchString, Mode=TwoWay}"
         ValueMemberBinding="{Binding Path=FullName}"
         ValueMemberPath="FullName"
         KeyUp="{ext:Invoke MethodName=Search, Source={Binding}}"/>

谢谢大家!

【问题讨论】:

    标签: silverlight xaml silverlight-5.0


    【解决方案1】:

    在代码中添加这样的处理程序:

    KeyEventHandler eventHandler = MyAutoCompleteBox_KeyDown;
    MyAutoCompleteBox.AddHandler(KeyDownEvent, eventHandler, true);
    

    【讨论】:

    • 嘿!谢谢,这几乎是解决方案,但是:a)我使用 XAML-Markup 因为我不想要代码并且我使用了 KeyUp,因为在 KeyDown 上的 Text 属性尚未更新。感谢并祝贺 50 分:D
    【解决方案2】:

    我不明白您为什么要使用 TextChanged 事件...?那是做什么用的?如果你把它拿出来,它会起作用吗?我在我的项目中使用了一个自动完成框,我不需要搜索方法......我所做的只是向自动完成框提供一个对象列表,并在用户键入时搜索该列表。我可以通过鼠标或向上/向下箭头进行选择。我唯一能想到的是,每次您尝试使用向上/向下箭头时,文本都会更改并触发搜索功能并关闭选择选项下拉...

    【讨论】:

    • 我用它来搜索,因为整个集合不能被 RIA 服务消化,而且数据太多(超过 10'000 个数据集)。
    猜你喜欢
    • 1970-01-01
    • 2011-08-07
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    相关资源
    最近更新 更多