2012-09-19 26 views
4

我有一個Button的MouseLeftButtonUp不火

<Button> 
    <Button.Template> 
     <ControlTemplate> 
      <StackPanel> 
       <Image Source="share.png" 
         MouseLeftButtonUp="Image_MouseLeftButtonUp" 
         MouseLeftButtonDown="Image_MouseLeftButtonDown" /> 
      </StackPanel> 
     </ControlTemplate> 
    </Button.Template> 
</Button> 

但問題是,不像的MouseLeftButtonDown的事件MouseLeftButtonUp不火。爲什麼?我該如何解決它?謝謝。

回答

7

可能是因爲Button正在處理事件,所以它不會過濾到Image控件。

爲什麼要處理Image上的MoustUp和MouseDown事件?爲什麼不在Button上處理它們?

編輯
快速瀏覽一下該事件的文件後,我看到了MouseLeftButtonUp路由策略是Direct,但實際根本事件是MouseUp事件具有Bubbling戰略,所以,實際上,MouseLeftButtonUp應該有一個事實上的冒泡策略,這意味着Image應該有機會在Button之前處理事件。

聽起來像別的東西可能會繼續。如果在圖像控件上將圖像設置爲空白,並且背景爲空(與Color.Transparent不同),則WPF會將控件視爲不存在,只要鼠標事件發生。

編輯2
嗯...也許我原來的猜測是正確的畢竟。根據此線程:
http://social.msdn.microsoft.com/forums/en/wpf/thread/e231919d-9fef-4aa5-9dcb-2c1eb68df25b/#306db880-ed50-45d2-819f-88d76f7148c1
Button正在處理MouseUp事件。嘗試使用PreviewMouseUp,然後檢查以查看哪個按鈕被點擊。

編輯3
好吧......我想我想通了。我打賭Button在MouseDown事件中「捕獲」鼠標。發生這種情況時,其他控件將不會收到MouseUp或MouseDown事件(包括預覽版本),直到鼠標被釋放。
請參閱:http://books.google.com/books?id=nYl7J7z3KssC&pg=PA146#v=twopage&q&f=true

+0

我必須使用這些事件來更改圖像源。即使使用Button事件MouseLeftButtonUp也不起作用。 – Nick

+0

謝謝,非常有用。 – Nick

+0

我相信'MouseLeftButtonUp'事件只是在'MouseUp'之後調用的。由於'Button'可能爲'MouseUp'設置'IsHandled'屬性爲'true',所以'MouseLeftButtonUp'可能永遠不會被提升。嘗試處理'Button'上的'MouseUp'。 (您甚至可能需要處理'PreviewMouseUp' - 不確定事件處理的順序。) – JDB

4

Click事件正在處理Cyborgx37所說的LeftMouseUp事件。

可以使用事件,而不是MouseLeftButtonUp,上按鈕,你可以看到下面:

<Button PreviewMouseLeftButtonUp="Button_PreviewMouseLeftButtonUp"> 
    <Button.Template> 
     <ControlTemplate> 
      <StackPanel> 
       <Image Source="..." /> 
      </StackPanel> 
     </ControlTemplate> 
    </Button.Template> 
</Button> 

你的按鈕模板只能有一個圖片,我想你不需要這個按鈕,你可以使用如上所述,所以你可以捕獲MouseLeftUp事件。

<Image MouseLeftButtonUp="Image_MouseLeftButtonUp" Source="..." /> 

這種方式非常容易,但它取決於你需要什麼。

順便說一句,對不起,我的廢話英語,我希望它可以幫助你。

0

嘗試使用事件PreviewMouseLeftButtonUp。