c# - 测试 UI/将焦点设置在 TextBox 上

标签 c# wpf ui-automation

我在测试 TextBox 的值时遇到问题。首先,我向您展示测试用例的代码:

[TestCase]
public void trage_kilogramm_ein()
{
    var windowPeer = new FrameworkElementAutomationPeer(this.zieleTest);
    var liste = windowPeer.GetChildren();
    var boxPeer = (TextBoxAutomationPeer)liste[34];
    boxPeer.VerifyAccess();
    var buttonPeer = (ButtonAutomationPeer)liste[9];
    var button = (Button)buttonPeer.Owner;
    var box = (TextBox)boxPeer.Owner;
    box.Visibility = Visibility.Visible;
    box.VerifyAccess();
    box.Focus();
    testWindow.Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action    (boxPeer.SetFocus));
    var args = new RoutedEventArgs(Button.ClickEvent, button);
    button.RaiseEvent(args);
    Assert.AreEqual("8", ((IValueProvider)boxPeer).Value);
}

我有一个包含 10 个文本框的窗口,您可以在其中输入值。我还有 10 个用于从 0 到 9 的数字的按钮,它们只发送特定数字的按键事件。在代码中,我模拟了数字/按钮“8”的点击事件。我的问题是我无法将焦点设置到 TextBox 上。我的测试总是失败,因为“TextBox.Text”仍然是“String.Empty”并且没有得到值“8”。

谢谢。

//编辑: 好的,现在我得到了重点。看来我需要将重点放在 parent 身上。 我写了两个方法来查看我是否获得了 KeyboardFocus。

private void Gewicht_obere_OnPreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    Console.WriteLine("Got Focus");
}

private void Gewicht_obere_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    Console.WriteLine("Focus Lost");
}

问题是现在我得到了焦点,但我很快就失去了它。

最佳答案

获取特定控件的引用(在这种情况下为 TextBox)。

Dispatcher.BeginInvoke((ThreadStart)delegate
            {
                control.Focus();
            });

关于c# - 测试 UI/将焦点设置在 TextBox 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22456635/

相关文章:

C# 检查 Datetime.now 是否为特定时间

c# - NHibernate 代码生成

c# - 在 mongodb 中执行高效的更新插入

wpf - 使用 MVVM Foundation Messenger 显示对话框

c# - UI 自动化 - 为另一个应用程序的 TextBox 设置文本

c# - 使用 Microsoft UI Automation 获取任何应用程序的 TitleBar Caption?

c# - 如何在 Zedgraph 中选择和放大 Masterpane

c# - WPF 命令 - 从 Window 和 UserControl 调用,相同的处理程序

c# - 了解使用 Windows native WPF 客户端进行 ADFS 登录

ios - 现在是否可以使用 Appium 自动化 App Store 应用程序