谁能告诉我如何以编程方式浏览WPF应用程序中的所有UI元素制表位?我想从第一个制表位开始嗅探相应的元素,访问下一个制表位,嗅探相应的元素,等等,直到我到达最后一个制表位。如何以编程方式导航WPF UI元素选项卡停止?
谢谢, 迈克 -
谁能告诉我如何以编程方式浏览WPF应用程序中的所有UI元素制表位?我想从第一个制表位开始嗅探相应的元素,访问下一个制表位,嗅探相应的元素,等等,直到我到达最后一个制表位。如何以编程方式导航WPF UI元素选项卡停止?
谢谢, 迈克 -
你做,因为这个所示MSDN文章这也解释了有关重点一切都在使用MoveFocus:Focus Overview。
下面是一些示例代码,以获得下一个重点元素(从该文章中获得,稍作修改)。
// MoveFocus takes a TraversalRequest as its argument.
TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Next);
// Gets the element with keyboard focus.
UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;
// Change keyboard focus.
if (elementWithFocus != null)
{
elementWithFocus.MoveFocus(request);
}
您可以使用MoveFocus调用完成此操作。您可以通过FocusManager获取当前关注的项目。以下代码将迭代窗口中的所有对象并将它们添加到列表中。请注意,这将通过切换焦点在物理上修改窗口。如果窗口不活动,代码很可能无法工作。
// Select the first element in the window
this.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
TraversalRequest next = new TraversalRequest(FocusNavigationDirection.Next);
List<IInputElement> elements = new List<IInputElement>();
// Get the current element.
UIElement currentElement = FocusManager.GetFocusedElement(this) as UIElement;
while (currentElement != null)
{
elements.Add(currentElement);
// Get the next element.
currentElement.MoveFocus(next);
currentElement = FocusManager.GetFocusedElement(this) as UIElement;
// If we looped (If that is possible), exit.
if (elements[0] == currentElement)
break;
}
上面的代码在我的WPF窗口中不起作用。该清单最终是空的。上面的第一个GetFocusedElement()调用返回null。我同意这段代码与文档完全一致,但不幸的是它并不适合我。我正在挖掘,找出原因。 – 2009-04-30 23:10:58
亲切,非常感谢! – lamarmora 2013-07-02 16:36:09