Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
727 views
in Technique[技术] by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...