Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Suggestion TextBox

I build a little WPF TextBox that checks it's content if it is valid. Now i want to implement the possibility to give suggestions. But not like the samples in the internet where a list with suggestions pops up. I am looking for a sample that does it with the selection of the TextBox like this:


If there is a specific name that i can look up or any sample code that you know, please let me know.

like image 860
Alexander Grasberger Avatar asked Mar 02 '26 08:03

Alexander Grasberger


1 Answers

After a lot of fighting with WPF, I have a proof of concept working for you:

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

MainWindow.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;
        }
    }
}

The next step would be to convert this into a user control, so you can set your suggestions through bindings, however you handle that.

like image 190
Adi Bradfield Avatar answered Mar 03 '26 21:03

Adi Bradfield