WPF:阻止用户离开TextBox?

时间:2011-06-15 18:33:48

标签: c# wpf event-handling focus

我赢得了其他战斗而失去了这一次 - 我们的设计有时会迫使用户进入战场。显然,代码示例过于简单。如果我需要在某处提供更多详细信息,请告诉我。

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

默认情况下,app会在textBox1上启动焦点/光标。该TextBox的PreviewLostKeyboardFocus处理程序阻止用户将焦点移动到带有键盘鼠标的textBox2。

但用户 能够用鼠标将焦点移动到comboBox1。

为什么用户可以使用鼠标将焦点移动到comboBox1,如何强制用户保留在textBox1中?

3 个答案:

答案 0 :(得分:1)

怎么样

    public MainWindow()
    {
        InitializeComponent();

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

答案 1 :(得分:1)

尝试:

comboBox1.IsHitTestVisible = false;

答案 2 :(得分:0)

您也可以在窗口级别处理它:

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