2 回答
TA贡献1820条经验 获得超10个赞
经过与 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>
主窗口.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;
}
}
}
下一步是将其转换为用户控件,以便您可以通过绑定设置您的建议,但您可以自行处理。
- 2 回答
- 0 关注
- 242 浏览
添加回答
举报