1

感谢对上一个问题(上一个问题)的回答,我现在有一段代码可以导航 WPF 制表位(如下所示)。除了第一个制表位外,它工作正常。调用 this.MoveFocus(...First) 后跟 FocusManager.GetFocusedElement 返回 null。有任何想法吗?如何在我的窗口中获得第一个制表位?

谢谢, - 迈克

// 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;
}
4

1 回答 1

1

我需要在我正在从事的项目中做类似的事情,我发现一些似乎工作得很好的东西。

这是一个带有代码的快速演示项目:

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>

代码背后:

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));
            };
        }
    }
}

我知道这真的是迟到的回应,但这对你有帮助吗?

于 2011-04-12T19:50:04.770 回答