2009-07-27 50 views

回答

1

确定这个页面你会找到一个解决方案,但如果你问我这有点讨厌: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/a420dc50-b238-4d2e-9209-dfbd98c7a060

它使用VisualTreeHelper创建所有控件的大列表,然后通过查看IsFocused属性询问他们是否有焦点。

我认为有一个更好的方法来做到这一点。 也许在WPF中搜索Active control或Focussed控件。

编辑: 本主题可能是有用的 How to programmatically navigate WPF UI element tab stops?

5
FocusManager.GetFocusedElement(this); // where this is Window1 

这里有一个完整的示例(当应用程序运行,注重一个文本框,然后回车)

XAML:

<Window x:Class="StackOverflowTests.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" KeyDown="window1_KeyDown" 
    Title="Window1" x:Name="window1" Height="300" Width="300"> 
    <StackPanel> 
     <TextBox x:Name="textBox1" /> 
     <TextBox x:Name="textBox2" /> 
     <TextBox x:Name="textBox3" /> 
     <TextBox x:Name="textBox4" /> 
     <TextBox x:Name="textBox5" /> 
    </StackPanel> 
</Window> 

C#

using System.Windows; 
using System.Windows.Input; 

namespace StackOverflowTests 
{ 
    /// <summary> 
    /// Interaction logic for Window1.xaml 
    /// </summary> 
    public partial class Window1 : Window 
    { 
     public Window1() 
     { 
      InitializeComponent(); 
     } 

     private void window1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) 
     { 
      if(e.Key == Key.Return) 
       MessageBox.Show((FocusManager.GetFocusedElement(this) as FrameworkElement).Name); 
     } 
    } 
} 
相关问题