WPF 建议文本框

Ale*_*ger 1 c# wpf autocomplete mvvm

我构建了一个小的 WPF TextBox 来检查它的内容是否有效。现在我想实现提供建议的可能性。但不像互联网上的示例那样弹出一个带有建议的列表。我正在寻找一个示例,它可以像这样选择 TextBox:


如果有我可以查找的特定名称或您知道的任何示例代码,请告诉我。

Adi*_*eld 6

经过与 WPF 的大量斗争,我有一个为您工作的概念证明:

主窗口.xaml

<Window x:Class="Solutions.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TextBox VerticalAlignment="Center" HorizontalAlignment="Center" x:Name="SuggestionBox" Width="200"
                 />
    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

主窗口.xaml.cs:

using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace Solutions
{
    public partial class MainWindow : Window
    {
        private static readonly string[] SuggestionValues = {
            "England",
            "USA",
            "France",
            "Estonia"
        };

        public MainWindow()
        {
            InitializeComponent();
            SuggestionBox.TextChanged += SuggestionBoxOnTextChanged;
        }

        private string _currentInput = "";
        private string _currentSuggestion = "";
        private string _currentText = "";

        private int _selectionStart;
        private int _selectionLength;
        private void SuggestionBoxOnTextChanged(object sender, TextChangedEventArgs e)
        {
            var input = SuggestionBox.Text;
            if (input.Length > _currentInput.Length && input != _currentSuggestion)
            {
                _currentSuggestion = SuggestionValues.FirstOrDefault(x => x.StartsWith(input));
                if (_currentSuggestion != null)
                {
                    _currentText = _currentSuggestion;
                    _selectionStart = input.Length;
                    _selectionLength = _currentSuggestion.Length - input.Length;

                    SuggestionBox.Text = _currentText;
                    SuggestionBox.Select(_selectionStart, _selectionLength);
                }
            }
            _currentInput = input;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

下一步是将其转换为用户控件,以便您可以通过绑定设置您的建议,但您可以自行处理。