In WPF most controls have MouseUp
and MouseDown
events (and the mouse-button-specific variations) but not a simple Click
event that can be used right away. If you want to have a click-like behaviour using those events you need to handle both which i consider to be a bit of a pain.
The obvious problem is that you cannot simply omit the MouseDown
event because if your click is started on another control and it is released over the control that only handles MouseUp
your supposed click will fire while it really should not: Both MouseUp
and MouseDown
should occur over the same control.
So i would be interested in a more elegant solution to this general problem if there is any.
Notes: There are several good solutions to this as can be seen below, i chose to accept Rachel's answer because it seems to be well received, but additionally i'd like to add the following annotations:
Rachel's button answer is quite clean and straightforward, but you need to wrap your actual control in a button and in some cases you might not really consider your control to be a button just because it can be clicked (e.g. if it is more like a hyperlink), further you need to reference a template every time.
Rick Sladkey's behaviour answer more directly answers the original question of how to just simulate a click/make a control clickable, the drawback is that you need to reference System.Windows.Interactivity
and like Rachel's solution it inflates the Xaml-code quite a bit.
My attached event answer has the advantage of being quite close to a normal click event in terms of Xaml-Markup which can be done with one attribute, the only problem i see with it is that the event-attachment in code is not cleanly encapsulated (if anyone knows a fix for that, please add a comment to the answer).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…