首页 > 解决方案 > 如何在输入时自动完成文本框?限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

如何确保当我在文本框中输入一个单词时,自动完成是实时的?

标签: c#.netwpf

解决方案


在 PreviewTextInput 处理程序中设置 e.Handled = true。“预览”意味着您将有机会在 TextBox 更改之前执行某些操作。将 e.Handled 设置为 true 将阻止 Input 事件更改 TextBox。

        e.Handled = true;

推荐阅读