我构建了一个WPF文本框,用于检查其内容是否有效。现在我想实现提出建议的可能性。但是不像互联网上出现的带有建议列表的示例。我正在寻找一个通过选择TextBox来做到这一点的示例,
答案 0 :(得分:2)
在与WPF进行了很多斗争之后,我有一个概念证明可以为您服务:
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;
}
}
}
下一步是将其转换为用户控件,因此您可以通过绑定设置建议,但是可以进行处理。
答案 1 :(得分:1)
您可以通过稍微修改here中的解决方案来使用水印(尤其是仅xaml的答案确实很简短)。只需将水印文本设置为您的第一个建议。然后,您可以添加一些功能,例如在后面的代码中按退格键时删除建议。