文本框自动填充/自动建议

时间:2020-01-31 14:03:57

标签: c# wpf xaml mvvm autocomplete

是否可以在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>

1 个答案:

答案 0 :(得分:0)

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

在我的脑海中,您可以创建一个隐藏的ListBox,该隐藏的TextBox会显示在您的建议中(请确保内容的大小为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。不过这条路要复杂得多。

希望这可以帮助您入门。

相关问题