C# 测试UI/在文本框上设置焦点
我在测试文本框的值时遇到问题。首先,我向您展示测试用例的代码:C# 测试UI/在文本框上设置焦点,c#,wpf,ui-automation,C#,Wpf,Ui Automation,我在测试文本框的值时遇到问题。首先,我向您展示测试用例的代码: [TestCase] public void trage_kilogramm_ein() { var windowPeer = new FrameworkElementAutomationPeer(this.zieleTest); var liste = windowPeer.GetChildren(); var boxPeer = (TextBoxAutomationPeer)liste[34];
[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.Text”仍然是“String.Empty”,并且没有得到值“8”
谢谢
//编辑:
好了,现在我明白了。看来我需要把重点放在父母身上。
我写了两个方法来看看我是否能获得键盘焦点
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");
}
现在的问题是我获得了焦点,但我立即失去了它。获取特定控件的引用(在这种情况下是文本框)
调度器上的BeginInvoke是一个异步调用。因此,可能是在设置焦点之前执行断言。如果只使用Dispatcher.Invoke,会得到相同的结果吗?结果仍然相同。谢谢
Dispatcher.BeginInvoke((ThreadStart)delegate
{
control.Focus();
});