问题
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.
回答1:
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.
回答2:
You could use a watermark by slightly modifying the solutions from here (especially the xaml-only answer is really short and simple). And just set the watermark text to your first suggestion. You could than add some functionality like removing the suggestion when pressing backspace in the code-behind.
来源:https://stackoverflow.com/questions/51684857/wpf-suggestion-textbox