问题非常简单:如何阻止LostFocus
在已经获得焦点的控件上MouseDown
被引发?
我有以下控件(所有事件绑定的临时测试):
<Grid Name="gBase" Focusable="True" MouseUp="SetFocus" MouseDown="SetFocus" MouseMove="gBase_MouseMove" PreviewDragEnter="gBase_PreviewDragEnter" LostFocus="gBase_LostFocus" GotFocus="gBase_GotFocus" Background="DarkRed" Width="500" Height="250" />
以下代码:
private void SetFocus(object sender, MouseButtonEventArgs e)
{
Grid g = sender as Grid;
g.Focus();
}
private void gBase_LostFocus(object sender, RoutedEventArgs e)
{
Grid g = sender as Grid;
g.Background = Brushes.DarkRed;
}
private void gBase_GotFocus(object sender, RoutedEventArgs e)
{
Grid g = sender as Grid;
g.Background = Brushes.Aquamarine;
}
private void gBase_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
Grid g = sender as Grid;
g.Focus();
}
}
private void gBase_PreviewDragEnter(object sender, DragEventArgs e)
{
Grid g = sender as Grid;
g.Focus();
}
这种行为几乎就是我想要达到的目标,如果我点击网格就可以获得焦点。
问题在于,如果Grid已经获得焦点,那么当我按下鼠标按钮并且在我释放或移动之前不会重新获得它时会失去它。我首选的行为是防止它首先失去焦点。
答案 0 :(得分:2)
问题是父ScrollViewer偷走了焦点。
这是通过使用事件MouseLeftButtonDown
并将MouseButtonEventArgs.Handled
设置为true
来解决,以防止进一步处理事件。
工作代码:
<Grid Name="gBase" Focusable="True" MouseLeftButtonDown="SetFocus" LostFocus="gBase_LostFocus" GotFocus="gBase_GotFocus" Background="DarkRed" MinWidth="500" MinHeight="250" Width="500" Height="250" HorizontalAlignment="Left" />
private void SetFocus(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
Grid g = sender as Grid;
g.Focus();
}
答案 1 :(得分:0)
使用某些属性或变量来存储实际关注的控件。在MouseDown比较之后,如果控件已经有焦点,如果是,那么就不要在LostFocus事件中执行代码。
重要的是在其他控件上更改焦点时更新存储属性。