2012-10-23 87 views
2

這是一個關係到SO Question 3222456 ....WPF用戶控件點擊

我創造我自己的用戶控件,上面有一些圖片和TextBlock中的,沒有別的。我想點擊整個UserControl時觸發一個事件。我的問題(或誤解)是,在WPF中,似乎只有MouseUp事件可以插入,沒有MouseClick。

那麼最佳做法是什麼?我可以找到所有的例子,就好像WPF中的mouseUp相當於點擊事件,但這是不對的。如果用戶在屏幕的一個部分中執行了鼠標下拉操作,將鼠標放在了我的控制之下,然後鬆開鼠標,該怎麼辦?即使它觸發了一個MouseUp事件,這並不是我的控件的點擊。

那麼如何獲得我的UserControl的真正MouseClick事件?

回答

2

一個非常簡單的方法是將您的整個內容放入一個幾乎爲空的模板的按鈕中,並回應Button的事件。

這看起來像

老:

<UserControl ...> 
    <Grid> ... </Grid> 
</UserControl> 

新:

<UserControl ...> 
    <Button OnClick="YourEventHandler"> 
     <Grid> ... </Grid> 
     <Button.Template> 
     <ControlTemplate x:Key="BlankButtonTemplate" TargetType="{x:Type ButtonBase}"> 
      <Border Background="#00000000"> 
      <ContentPresenter Margin="{TemplateBinding Padding}" 
           HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
           VerticalAlignment="{TemplateBinding VerticalContentAlignment}" /> 
      </Border> 
     </ControlTemplate> 
     </Button.Template> 
    </Button> 
</UserControl> 
+1

感謝@Jens,這看起來很有希望,我給一個嘗試。你經常使用這種技術嗎?我看到它會如何工作,但它看起來像一團糟。 – sisdog

+0

我確實頻繁使用它。您可以使用其中的模板創建一個ControlTemplate資源,然後只需使用

2

爲什麼不直接使用的MouseDown?

把事件的用戶控制和簡單的做到這些:

private void MyControl_MouseDown(object sender, MouseButtonEventArgs e) 
{ 
    if (e.ChangedButton == MouseButton.Left) 
    { 
     MessageBox.Show("Clicked!"); 
    } 
}