【问题标题】:Textbox Autocomple/Autosuggestions文本框自动完成/自动建议
【发布时间】:2020-05-17 05:06:59
【问题描述】:

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

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

【问题讨论】:

  • Is it possible to add somehow autocomplete suggestions to textbox in a WPF application。你能告诉我们你尝试了什么吗,上面的代码不能保证你在问什么。
  • 我什么都没试过,只是做了一些研究,但我没有找到任何关于简单文本框的内容
  • i tried nothing yet,请在发帖前做。我们帮助解决特定问题的用户已经尝试过。现在的问题似乎是寻求更多的“为我编码”
  • 我尝试使用带有自动完成框的外部库,但不想为此购买许可证
  • 你真的找到了nothing freeNothing? Nothing at all?

标签: c# wpf xaml mvvm autocomplete


【解决方案1】:

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

在我的脑海中,您可以创建一个隐藏的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。不过这条路要复杂得多。

希望这能让你开始。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-21
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 2012-11-15
    • 2016-04-27
    • 1970-01-01
    • 2016-01-20
    相关资源
    最近更新 更多