XAML 单击另一个按钮时PreviewMouseMove事件不起作用

bvn4nwqk  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(151)
<Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Button Grid.Column="0" Background="Red"></Button>
        <Grid Grid.Column="1" Name="BlueGrid" Background="Blue" PreviewMouseMove="Grid_PreviewMouseMove"></Grid>
    </Grid>
private void Grid_PreviewMouseMove(object sender, MouseEventArgs e)
 {
      var pos = Mouse.GetPosition(BlueGrid);
 }

所以在这个窗口里有一个网格。每次鼠标在蓝色网格上时,我都要获得鼠标的位置。它工作得很好,但它只有一个问题。当你点击按钮(红色按钮),并按住它,你进入网格的事件不工作了。
我尝试了其他事件,如MouseMove,MouseEnter和DragEnter,但它们都不起作用。有没有什么我可以做的,以获得鼠标的位置,网格无论什么?

sbdsn5lh

sbdsn5lh1#

解释是当你点击一个ButtonBase时,控件会捕获鼠标。这意味着所有鼠标输入事件都使用ButtonBase作为源,即使鼠标输入事件是在元素边界之外触发的。
解决方案是在公共父容器上侦听路由的鼠标输入事件,并使用CaptureMode.SubTree控制鼠标捕获。
您可以通过访问RoutedEventArgs.Source属性来标识感兴趣的事件源:

<Grid PreviewMouseMove="Grid_PreviewMouseMove">
  <Grid.ColumnDefinitions>
    <ColumnDefinition />
    <ColumnDefinition />
  </Grid.ColumnDefinitions>

  <Button Grid.Column="0"
          Background="Red" />
  <Grid x:Name="BlueGrid" 
        Grid.Column="1"
        Background="Blue" />
</Grid>
private void Grid_PreviewMouseMove(object sender, MouseEventArgs e)
{
  // Capture mouse for the complete sub tree instead for a single element.
  // In this case this includes the Button and the Grid.
  // Because messing with the mouse capture could potentially break 
  // the ButtonBase.Click event and ButtonBase.Command handling 
  // you may have to fallback to use the UIElement.PreviewMouseLeftButtonUp event 
  // to execute the Button.
  _ = Mouse.Capture(this, CaptureMode.SubTree);

  // Filter the event source to handle BlueGrid mouse move events
  if (e.Source is Grid grid 
    && grid.Name.Equals("BlueGrid", StringComparison.OrdinalIgnoreCase))
  {
    // TODO::Handle mouse move over BlueGrid
  }

  // Relasae mouse capture
  _ = Mouse.Capture(null);
}

相关问题