2009-07-27 47 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); 
     } 
    } 
} 
相關問題