You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF中PreviewTextInput事件需输入额外字符才触发方法的问题

问题解决方法

问题根源

PreviewTextInput事件触发时,输入的字符还未被写入TextBox.Text属性。比如输入"Algorithm"的最后一个字符"m"时,textBox.Text此时还是"Algorith",只有当你再输入下一个字符时,Text才会更新为"Algorithm"+新字符,这时候判断条件才会成立。

方案1:改用TextChanged事件(推荐)

TextChanged事件会在TextBox.Text属性真正更新后触发,能实时获取最新输入内容,完美解决延迟判断问题。

示例代码:

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    var textBox = sender as TextBox;
    if (textBox?.Text == "Algorithm")
    {
        ValueList.Clear(); // 避免重复添加相同选项
        ValueList.Add("Pixel");
        ValueList.Add("O2");
    }
    else
    {
        // 输入内容不符合时,可清空下拉选项
        ValueList.Clear();
    }
}

方案2:在PreviewTextInput中模拟输入后的文本

如果必须保留PreviewTextInput事件,可手动将当前输入的字符插入到文本框的对应位置,模拟输入完成后的文本内容再做判断:

示例代码:

private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    var textBox = sender as TextBox;
    if (textBox == null) return;

    // 拼接当前输入字符到文本框现有内容的选中位置,得到输入后的完整文本
    string inputAfterText = textBox.Text.Insert(textBox.SelectionStart, e.Text);
    if (inputAfterText == "Algorithm")
    {
        ValueList.Clear();
        ValueList.Add("Pixel");
        ValueList.Add("O2");
    }
}

额外注意事项

  • 若要处理删除字符、粘贴文本等操作,TextChanged事件会更可靠,因为PreviewTextInput不会响应这些操作。
  • 每次更新下拉选项前记得调用ValueList.Clear(),避免重复添加相同选项。

内容的提问来源于stack exchange,提问作者Henok Woldemichael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 01:59:58