Reputation: 13206
How do you get the name of the textbox currently in focus on XAML applications?
I've tried the below, but keep getting the following error message: Object reference not set to an instance of an object
. What am I doing wrong?
var textbox = Keyboard.FocusedElement as TextBox;
MessageBox.Show(textbox.Name);
Upvotes: 0
Views: 180
Reputation: 66439
If the element that has focus is not a TextBox
, you're going to get the exception you're seeing, so you should test for that:
var textbox = Keyboard.FocusedElement as TextBox;
if (textbox != null)
MessageBox.Show(textbox.Name);
Also, if this code is being executed in a button click (for example), you'll have to make sure the button can't steal focus from whatever element currently has it by setting "Focusable" to false:
<Button Content="Press" Focusable="False" Command="{Binding Path=PressCommand}" />
Upvotes: 1