誰能告訴我如何以編程方式瀏覽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