在边界WPF MVVM外部检测鼠标左键(单击)

时间:2017-07-25 15:28:56

标签: wpf xaml mvvm mouseleftbuttondown

我在MVVM中有一个边框。我想要实现的是在边界外检测鼠标左键然后隐藏它。我可以在主窗口的MouseLeftButtonDown事件中执行此操作,但我不知道它是否是最佳解决方案。我怎么能这样做?我想避免这种点击干扰其他事件,例如,这个边框放在一个堆叠面板中,并且鼠标左键双击时会隐藏堆栈面板。

<Border Grid.Row="2" 
     x:Name="customPopup" 
     CornerRadius="10,10,0,0" 
     Height="25" Margin="0"
     HorizontalAlignment="Center" 
     VerticalAlignment="Center"
     Width="Auto"
     BorderBrush="DarkBlue" 
     BorderThickness="1"  
     Background="AntiqueWhite">
    <StackPanel  Orientation="Horizontal" 
                 HorizontalAlignment="Center">
        <Image Source="/Common.Images;component/Images/Info.png" 
               Height="20" 
               Width="20" Stretch="Fill"/>
        <TextBlock Margin="5" 
                   VerticalAlignment="Center" 
                   HorizontalAlignment="Left" 
                   Background="Transparent" 
                   FontSize="12">
                  <Run Text="Click outside to close it"/>
        </TextBlock>
    </StackPanel>
</Border>

1 个答案:

答案 0 :(得分:0)

在窗口上使用MouseDown可能是获得所需结果的最佳选择。您需要进行一些计算才能查看光标是否在边框之外。类似的东西:

private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
    // get positions
    Point mouseLoc = Mouse.GetPosition(null);
    Point borderLoc = customPopup.TranslatePoint(new Point(0,0), null);

    // check if the mouse is outside the border
    if((mouseLoc.X < borderLoc.x || mouseLoc.X > (borderLoc.X + customPopup.ActualWidth)) && (mouseLoc.Y < borderLoc.Y || mouseLoc.Y > borderloc.Y + customPopup.ActualHeight))
    {
        // hide the border
    }
}

然后要处理双击,请使用PreviewMouseDoubleClick。由于预览事件是隧道而不是冒泡,因此即使您在同一元素上有单击事件,也应该调用双击。

private void Window_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
     // double click code...
     e.Handled = true;
}