What is the best way to simulate a Click with MouseUp & MouseDown events or otherwise?

H.B. picture H.B. · Jan 28, 2011 · Viewed 14.2k times · Source

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

Answer

Rachel picture Rachel · Jan 28, 2011

I would use a Button control and overwrite the Button.Template to just show the content directly.

<ControlTemplate x:Key="ContentOnlyTemplate" TargetType="{x:Type Button}">
    <ContentPresenter />
</ControlTemplate>

<Button Template="{StaticResource ContentOnlyTemplate}">
    <Label Content="Test"/>
</Button>