c# - 如何在输入时自动完成文本框?限3个字?
问题描述
我有以下要选择的词:
string standard = "select a part of the text in the textbox";
当有人在上面的字符串中键入任何字母时,一次选择 3 个单词,直到到达结尾。
例如,这个人输入了字母“o”,所以我要选择第一个字母“o”加上前面的 3 个单词,直到我完成为止。
我使用该事件制作了一个脚本PreviewTextInput
,问题是它无法捕获键入的空间,而且当我在文本框中键入一个字母时,它在前面重复并且不选择其余 3 个单词。
CS
string typed = "";
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
string standard = "select a part of the text in the textbox";
typed += e.Text;
this.textBox1.Text = typed;
int indexOf = standard.IndexOf(typed, StringComparison.OrdinalIgnoreCase);
if (indexOf >= 0)
{
string start = standard.Substring(indexOf + typed.Length);
string[] s = start.Split(' ');
for (int i = 0; i < s.Length; i++)
{
if (i < 3) this.textBox1.Text += $"{s[i]} ";
else break;
}
}
this.textBox1.Focus();
this.textBox1.SelectionStart = typed.Length;
this.textBox1.SelectionLength = this.textBox1.Text.Length - typed.Length;
}
XAML
<Window x:Class="WpfApp1.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"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<TextBox Name="textBox1" HorizontalAlignment="Left" Height="18" Margin="143,107,0,0" TextWrapping="NoWrap" Text="" VerticalAlignment="Top" Width="308" PreviewTextInput="TextBox_PreviewTextInput"/>
</Grid>
</Window>
如果我采用与上面相同的代码并将其放入Windows Forms
事件KeyPress
方法中,它将起作用。但为什么它不起作用WPF
?
如何确保当我在文本框中输入一个单词时,自动完成是实时的?
解决方案
在 PreviewTextInput 处理程序中设置 e.Handled = true。“预览”意味着您将有机会在 TextBox 更改之前执行某些操作。将 e.Handled 设置为 true 将阻止 Input 事件更改 TextBox。
e.Handled = true;
推荐阅读
- arm - Arm Mali GPU 中的点积是否比 MAD(乘加)指令更快?
- html - 有没有办法检索网页的最终渲染像素值?
- java - Spring WebFlux 测试抛出“IllegalStateException: Failed to load ApplicationContext”异常
- java - 如何在不出现实例化异常的情况下将此超类更改为抽象类?
- node.js - 如何修复 Gatsby JS 上的错误 R10(引导超时)?
- r - 使用粘贴在 R 中循环以绘制图形
- python - 在numpy中将数组拼接在一起
- c# - WPF - ProgressBar 仅在进程完成之前更新
- angular - Angular - 在调试中上传照片,导致网站重新编译
- bots - 什么是 nbot,为什么它会抓取我的网站?