找到第一个WPF制表位

找到第一个WPF制表位

本文介绍了找到第一个WPF制表位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

谢谢,-迈克

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

推荐答案

我需要在正在从事的项目中做类似的事情,但发现有些事情似乎已经足够好了.

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>

后面的代码:

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?

这篇关于找到第一个WPF制表位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 08:53