问题描述
我想模拟用户对 WPF 文本框的输入.我想输入一个字符,以便触发 OnPreviewTextInput 事件.我尝试通过 Text 属性设置 Text,但这并没有触发事件:
I want to simulate user input to a WPF TextBox. I want to input a character such that the OnPreviewTextInput event is triggered. I tried setting the Text through the Text property, but this didn't trigger the event:
public void SomeFunction()
{
var textBox = new TextBox();
textBox.Text = "A";
}
我可以以某种方式显式触发事件吗?
Can I trigger the event explicitly somehow?
推荐答案
查看 如何在 C# 中以编程方式生成按键事件? 以很好地描述如何模拟输入事件.
See the answer to How can I programmatically generate keypress events in C#? for a good description of how to simulate input events.
你也可以这样做:
TextCompositionManager.StartComposition(
new TextComposition(InputManager.Current, textBox, "A"));
这将引发 PreviewTextInput 事件,然后引发 TextInput 事件并更改文本.
This will raise the PreviewTextInput event and then raise the TextInput event and change the text.
这篇关于如何模拟 WPF 文本框的文本输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!