2017-07-25 94 views
0

我在MVVM中有一個邊框。我試圖實現的是在邊框外部檢測鼠標左鍵,然後隱藏它。我可以在主窗口的MouseLeftButtonDown事件中完成它,但我不知道它是否是最佳解決方案。我怎麼能這樣做?我想避免這種點擊干擾其他事件,例如,這個邊框被放置在一個堆疊面板中,並且堆疊面板被隱藏在鼠標左鍵上雙擊。在邊框外部檢測鼠標左鍵(單擊)WPF MVVM

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

回答

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; 
} 
+0

我還沒有看到任何方法與您發佈的簽名。有以下簽名:私人無效Window_PreviewMouseDown(對象發件人,MouseButtonEventArgs e)它也不工作,因爲我的雙擊事件(它隱藏stackpanel)不工作然後。 – user1624552

+0

將我的隧道/冒泡事件混淆起來,檢查我的編輯 –

+0

在Window_MouseDown中,您使用&&它應該是||。另外,當單擊外部自定義彈出窗口時,並不總是被隱藏,例如,如果我單擊按鈕或在文本框中單擊,則彈出窗口不會被隱藏。當點擊彈出窗口外UI中的任何控件時,我想隱藏。我該如何解決這個問題? – user1624552