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
979 views
in Technique[技术] by (71.8m points)

c# - WPF combining MouseDown and TouchDown to same event

I am developing an app which will be used on a laptop with touch screen. Hence MouseDown events are essentially doing the same action, how should this be done.

The code I have written something like this -

XAML

<Button MouseDown="Button_OnMouseDown" TouchDown="Button_OnTouchDown"/>

C#

private void Button_OnMouseDown(object sender, MouseButtonEventArgs e)
{
    Action();
}
private void Button_OnTouchDown(object sender, TouchEventArgs e)
{
    Action();
}
private void Action()

Is there a better way to do this? Any feedback is appreciated.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Make eventArgs to be more generic one. Use EventArgs in place of MouseEventArgs and TouchEventArgs.

private void Button_OnMouseDownOrTouchDown(object sender, EventArgs e)
{
    Action();
}

and now you can hook to same event from XAML:

<Button MouseDown="Button_OnMouseDownOrTouchDown" 
        TouchDown="Button_OnMouseDownOrTouchDown"/>

That's called Contravariance on delegates. Read more about here.

Delegates can be used with methods that have parameters of a type that are base types of the delegate signature parameter type. With contravariance, you can use one event handler instead of separate handlers. For example, you can create an event handler that accepts an EventArgs input parameter and use it with a Button.MouseClick event that sends a MouseEventArgs type as a parameter, and also with a TextBox.KeyDown event that sends a KeyEventArgs parameter.


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

...