Reputation: 521
I have a user control that has a TextBox
on it. If I set focus on the TextBox
in the constructor, then the TextBox
works as expected. Sometimes though, I don't want the TextBox
to have focus when the user control is first shown, and so I added a property to the user control which sets focus to the TextBox
. This works, although I get the problem that I can't then reset focus on the TextBox
after it has lost focus.
Doesn't anyone have any ideas why this might be happening?
public ucQueryBox()
{
InitializeComponent();
// Set default values for properties
CodePrompt = "Barcode";
TextBoxFontSize = 20;
TextBoxMaxWidth = 0;
Label = "";
LabelFontSize = 20;
LabelForeground = Colors.White.ToString();
KeyboardButtonVisibility = Visibility.Visible;
txtSelection.Focus();
}
/// <summary>
/// Allows user to decide whether or the user control should have focus when it loads
/// Focus puts the green boarder around the textbox
/// </summary>
[Browsable(true)]
public Boolean SetFocusOnLoad
{
get { return _bSetFocusOnLoad; }
set
{
_bSetFocusOnLoad = value;
if (_bSetFocusOnLoad)
txtSelection.Focus();
}
}
Upvotes: 1
Views: 872
Reputation: 12811
Focus in WPF is a complex topic. I think you'll find that the proper way to do what you want is to use FocusManager
in your XAML:
<UserControl ... FocusManager.FocusedElement="{Binding ElementName=myTextBox}">
<TextBox x:Name="myTextBox" />
</UserControl>
If you use FocusManager
like this to establish all focus requirements (that is, you use FocusManager on all Windows and UserControls that have any sort of focus requirements), then you'll probably find that all the focusing works exactly like you expect.
Upvotes: 1