I need to be able to handle the double click and single click event on the WPF StackPanel. But there is no such thing as the StackPanel's DoubleClick Event. I want to do 2 different operations in these 2 EventHandlers.
Any idea how to do that?
Thank you
The best way is to right your own mouse button handler with a timeout - if the event is fired again within the timeout period, then fire your doubleclick message, otherwise call the single click handler. Here's some sample code (Edit: originally found here):
Then, in the control you want to receive the events:
Then in the event handler:
Should work. Note that single clicking in the StackPanel would hit the event (but fail the if check)
...years later. @MoominTroll's solution is perfectly acceptable. Another option is to wrap the stack panel in a content control that supports the double click event.
Another option is to add a MouseBinding to the InputBindings on the StackElement and then add a CommandBinding that gets activated by MouseBinding. On the whole this is a better practice than event based mechanisms because it avoids the memory leak issues caused by strong references. It also provides for separation of command logic from the representation.
That being said, its not as straight forward and attaching to the event makes for a great shortcut.
And it goes without saying, make your stackpanel background at least transparent or it won't be caught by the mouse click hit test when you click on the "background". Null backgrounds are skipped over by hit detection.
I had a similar problem (respond to single click event and do an additional work in case of double click event). I solved the problem this way:
1) define and declare some integer to hold last click timestamp
2) in Window_Loaded method initialize previously declared variable with some number greater than 200
3) add mouse button handler to your stack panel
4) add following method
This code is useless if you need to separately detect single click and double click event. That situation introduces a bit more complexity, but definitly can be solved.
There is an easier solution to do this.
In StackPanel's event PreviewMouseLeftDown (for example), you can check if MouseButtonEventArgs.ClickCount property has a value of 2. 1 = Single click 2 = Double Click