简体   繁体   中英

WPF: prevent user from leaving TextBox?

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?

How about

    public MainWindow()
    {
        InitializeComponent();

        textBox1.Focus();
        textBox1.LostFocus += (s, e) => 
                   Dispatcher.BeginInvoke((Action)(() => textBox1.Focus()));
    }

?

Try:

comboBox1.IsHitTestVisible = false;

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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM