问题描述
|
我赢得了其他战斗,但输掉了这场战斗-我们的设计有时会迫使用户进入战场。显然,代码示例过于简化。让我知道是否需要在某处提供更多详细信息。
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\" Name=\"textBox1\" />
<TextBox Height=\"23\" Margin=\"5,65,0\" Name=\"textBox2\" />
<ComboBox Height=\"23\" Margin=\"5,125,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;
}
}
}
默认情况下,该应用在textBox1上启动时带有焦点/光标。该TextBox的PreviewLostKeyboardFocus处理程序可防止用户通过键盘或鼠标将焦点移至textBox2。
但是用户可以用鼠标将焦点移到comboBox1。
用户为何能够使用鼠标将焦点移至comboBox1,以及如何强制用户保留在textBox1中?
解决方法
尝试:
comboBox1.IsHitTestVisible = false;
, 怎么样
public MainWindow()
{
InitializeComponent();
textBox1.Focus();
textBox1.LostFocus += (s,e) =>
Dispatcher.BeginInvoke((Action)(() => textBox1.Focus()));
}
?
, 您也可以在窗口级别处理它:
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;
}