1

问题很简单:我如何防止在已经获得焦点的控件上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 它就会获得焦点。

问题是,如果 Grid 已经获得焦点,它会在我按下鼠标按钮时失去它,直到我释放或移动它才会重新获得它。我更喜欢的行为是首先防止它失去焦点。

4

2 回答 2

2

问题是父 ScrollViewer 偷走了焦点。

这是通过使用事件MouseLeftButtonDown并将 设置MouseButtonEventArgs.Handledtrue以防止进一步处理事件来解决的。

工作代码:

<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();
}
于 2012-10-23T10:07:48.747 回答
0

使用一些属性或变量来存储哪个控件具有实际焦点。并且在 MouseDown 比较控件是否已经具有焦点之后,如果是这样,则不要在 LostFocus 事件中执行代码。

重要的是更新存储属性,当焦点转移到其他控件上时。

于 2012-10-23T09:34:55.657 回答