Detect mouse left button down (Click) outside a border WPF MVVM

1.4k Views Asked by At

I have a border in MVVM. What I am trying to achieve is to detect mouse left button down outside the border and then hide it. I can do it within the MouseLeftButtonDown event for main window, but I do not know if it is the best solution. How could I do this? I want to avoid this click to interfere with other events, for example, this border is placed in a stackpanel and the stackpanel is being hidden on mouse left button double click.

<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

There are 1 best solutions below

4
On

Using MouseDown on the window is probably your best bet to get your desired results. You'll need to do some calculations in order to see if the cursor is outside of the border. Something like:

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
    }
}

Then to handle the double click, use PreviewMouseDoubleClick. Since Preview events are tunneling rather than bubbling, the double click should get called even if you have a single click event on the same element.

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