Reputation: 16382
I won other battles and lost this one -- wherein our design sometimes forces users to fields. Obviously the code samples are oversimplified. Let me know if I need to provide more details somewhere.
XAML:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<TextBox Height="23" Margin="5,5,0,0" Name="textBox1" />
<TextBox Height="23" Margin="5,65,0,0" Name="textBox2" />
<ComboBox Height="23" Margin="5,125,0,0" Name="comboBox1" >
<ComboBoxItem Content="Lorem Ipsum" />
</ComboBox>
</Grid>
</Window>
XAML.CS:
using System.Windows.Input;
namespace WpfApplication1 {
public partial class MainWindow {
public MainWindow() {
InitializeComponent();
textBox1.Focus();
textBox1.PreviewLostKeyboardFocus += Foo;
}
void Foo(object sender, KeyboardFocusChangedEventArgs e) {
e.Handled = true;
}
}
}
The app launches w/ the focus/cursor on textBox1 by default. The PreviewLostKeyboardFocus handler of that TextBox prevents the user from moving focus to textBox2 w/ either the keyboard or the mouse.
But the user is able, with the mouse, to move the focus to comboBox1.
Why is the user able to move the focus to comboBox1 using the mouse, and how can I force the user to remain in textBox1?
Upvotes: 4
Views: 3758
Reputation: 109027
How about
public MainWindow()
{
InitializeComponent();
textBox1.Focus();
textBox1.LostFocus += (s, e) =>
Dispatcher.BeginInvoke((Action)(() => textBox1.Focus()));
}
?
Upvotes: 1
Reputation: 5445
You can also just handle it on the window level:
public MainWindow()
{
InitializeComponent();
textBox1.Focus();
this.PreviewMouseDown += new MouseButtonEventHandler(MainWindow_PreviewMouseDown);
this.PreviewKeyDown += new KeyEventHandler(MainWindow_PreviewKeyDown);
}
void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab) e.Handled = true;
}
void MainWindow_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
}
Upvotes: 0