I have some textboxes where I would like focus to behave a little differently than normal for a WPF application. Basically, I would like them to behave more like a textbox b
you cant explicitly loose the focus of a control
you can set the focus to other control instead
**txt.Focusable=true;
label.focus();
Keyboard.Focus(txtPassword);**
try this
I was running into a similar issue, but when I wrapped a ScrollViewer control around my textboxes , all the textboxes would automatically lose focus when clicking anywhere outside the texboxes.
I think, better way to solve this problem is adding MouseDown event handler to window with code behind:
private void window_MouseDown(object sender, MouseButtonEventArgs e)
{
Keyboard.ClearFocus();
}
I'm not 100% sure, but if you set Focusable
to true on the container element (Grid, StackPanel, etc) then it should take the focus away from the text box.
You can use the IsKeyboardFocusedChanged
event:
myTextBox.IsKeyboardFocusedChanged += myTextBox_IsKeyboardFocusedChanged;
private void SendFileCaptionTextBox_IsKeyboardFocusedChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue.ToString() == "True")
{
// it's focused
}
else
{
// it's not focused
}
}
You can register the PreviewMouseLeftButtonDownEvent
to every type of element in App.xaml.cs on application startup.
EventManager.RegisterClassHandler(typeof(UIElement), UIElement.PreviewMouseLeftButtonDownEvent,
new MouseButtonEventHandler(FocusElement));
private void FocusElement(object sender, MouseButtonEventArgs e)
{
var parent = e.OriginalSource as DependencyObject;
if (parent is UIElement element && !element.Focusable)
{
element.Focusable = true;
element.Focus();
element.Focusable = false;
}
}