问题
Thanks to an answer on a previous question (Previous Question), I now have a body of code that navigates WPF tab stops (shown below). It works fine except for the first tab stop. Calling this.MoveFocus(...First) and followed by FocusManager.GetFocusedElement returns null. Any ideas? How do I get the first tab stop in my window?
Thanks, - Mike
// 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;
}
回答1:
I needed to do something similar in a project I'm working on, and I found something that seems to work well enough.
Here's a quick demo project with the code:
XAML:
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication3"
Title="MainWindow" SizeToContent="WidthAndHeight">
<StackPanel>
<TextBox Width="200" />
<TextBox Width="200" />
<TextBox Width="200" />
</StackPanel>
</Window>
Code Behind:
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
namespace WpfApplication3
{
public partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
// Code needs window to be active to work, so just call it in Loaded event for demo
this.Loaded += (s, e) =>
{
FocusManager.SetFocusedElement(this, this);
UIElement element = FocusManager.GetFocusedElement(this) as UIElement;
element.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
};
}
}
}
I know this is really late response, but does this help you at all?
来源:https://stackoverflow.com/questions/809622/locating-the-first-wpf-tab-stop