C# 发送到WPF TextBox的KeyDown事件不会触发文本输入

C# 发送到WPF TextBox的KeyDown事件不会触发文本输入,c#,wpf,C#,Wpf,我试图模拟WPF文本框控件的键盘输入(这样做的原因超出了这个问题的范围)。然而,我很难让文本出现 我制作了一个简单的WPF应用程序,其中包含一个按钮和一个文本框,我希望在单击按钮时模拟键盘按下,从而在文本框中键入一个文本字符(字母“a”)。这就是我到目前为止所做的: private void button_Click(object sender, RoutedEventArgs e) { var key = Key.A; var target = textBox1; // Key

我试图模拟WPF文本框控件的键盘输入(这样做的原因超出了这个问题的范围)。然而,我很难让文本出现

我制作了一个简单的WPF应用程序,其中包含一个按钮和一个文本框,我希望在单击按钮时模拟键盘按下,从而在文本框中键入一个文本字符(字母“a”)。这就是我到目前为止所做的:

private void button_Click(object sender, RoutedEventArgs e)
{
    var key = Key.A;
    var target = textBox1; // Keyboard.FocusedElement;

    // None of these actually induce text to appear in the textbox
    target.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual((Visual)target), 0, key) { RoutedEvent = Keyboard.PreviewKeyDownEvent });
    target.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual((Visual)target), 0, key) { RoutedEvent = Keyboard.PreviewKeyUpEvent });
    target.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual((Visual)target), 0, key) { RoutedEvent = Keyboard.KeyDownEvent });
    target.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual((Visual)target), 0, key) { RoutedEvent = Keyboard.KeyUpEvent });
}
我已经尝试将事件处理程序附加到textbox,并且我可以查看并验证textbox是否正在接收事件。但是,它们实际上都没有显示任何文本。

如何通过引发事件来触发文本输入


非常感谢您的帮助。

您是否尝试过获取控件的AutomationPeer,例如:

TextBox tb;
TextBoxAutomationPeer tbap = new TextBoxAutomationPeer(tb);

IValueProvider vp = tbap.GetPattern(PatternInterface.Value) as IValueProvider;
vp.SetValue("Your text here.");

您是否尝试过获取控件的AutomationPeer,例如:

TextBox tb;
TextBoxAutomationPeer tbap = new TextBoxAutomationPeer(tb);

IValueProvider vp = tbap.GetPattern(PatternInterface.Value) as IValueProvider;
vp.SetValue("Your text here.");

也许这个有帮助:target.Text+=“A”;嗯,也许这些原因都在范围之内。我正试图向当前关注的控件发送一个键盘事件。如您所述,设置.Text会破坏它的任何绑定。也许这一个有帮助:target.Text+=“A”;嗯,也许这些原因都在范围之内。我正试图向当前关注的控件发送一个键盘事件。正如您所描述的,setting.Text会破坏它的任何绑定。