我在测试 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/