温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - Textbox Autocomple/Autosuggestions
c# mvvm wpf xaml autocomplete

c# - 文本框自动填充/自动建议

发布于 2020-04-05 20:30:23

是否可以在WPF应用程序中以某种方式向文本框添加自动完成建议?就像我将建议绑定到DataTable或字符串列表的位置一样?文本框可以吗?

 <TextBox Text="{Binding InputText, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
                     HorizontalAlignment="Stretch"
                     VerticalAlignment="Stretch"
                     VerticalContentAlignment="Center" >
        <TextBox.InputBindings>
          <KeyBinding Command="{Binding EnterKeyPressedCommand}" Key="Return" />
        </TextBox.InputBindings>
      </TextBox>

查看更多

提问者
DataLordDev
被浏览
119
David Bentley 2020-01-31 23:20

如果您在寻找起点时遇到困难,实际上涉及几个步骤,并且可能有几种方法可以做到这一点。

在我的头顶上方,您可以创建一个隐藏的内容ListBoxTextBox其中包含您的建议(请确保ListBox内容大小)。随着文本的更改,您可以使用一个简单的TestChanged事件。

XAML:

<TextBox x:Name="someTextbox" 
    TextChanged="someTextbox_TextChanged"
</TextBox>

背后的代码:

    private void someTextbox_TextChanged(object sender, TextChangedEventArgs e)
    {
        // Call method to check for possible suggestions.
        // Display Listbox with suggested items.
    }

然后,单击中的项目Listbox将更新文本。
注意:当用户从菜单中选择建议时,您将需要某种方式来防止事件运行逻辑ListBox

现在用于MVVM:

private string _SomeTextbox = "";
public string SomeTextbox
{
    get { return _SomeTextbox; }
    set
    {
        _SomeTextbox = value;
        OnPropertyChanged(new PropertyChangedEventArgs("SomeTextbox"));

        // Call method to check for possible suggestions.
        // Display Listbox with suggested items.
    }
}

使用MVVM,您可以ListBox相对轻松地绑定可见性和内容,然后根据需要进行显示。

执行此操作的一种方法是将TextBox默认设置编辑为内置ListBox不过,这条路要复杂得多。

希望这可以帮助您入门。