I there a way to know which item has the focus in and WPF application? Is there a way to monitor all events and methods calls in wpf?
+6
A:
FocusManager.GetFocusedElement(this); // where this is Window1
Here's a full sample (when the app runs, focus a textbox and hit enter)
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);
}
}
}
Carlo
2009-07-27 15:39:27
+1
A:
ok on this page you'll find a solution but it's a bit nasty if you ask me: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/a420dc50-b238-4d2e-9209-dfbd98c7a060
It uses the VisualTreeHelper to create a big list of all the controls out there and then asks them is they have the focus by lookin at the IsFocused property.
I would think that there is a better way to do it. Perhaps do a search for Active control or Focussed control in combination with WPF.
EDIT: This topic might be useful http://stackoverflow.com/questions/809382/how-to-programmatically-navigate-wpf-ui-element-tab-stops
Zyphrax
2009-07-27 15:41:37