Locating the first WPF tab stop

别来无恙 提交于 2019-12-24 07:15:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!