WPF将MouseDown和TouchDown组合到同一事件

编程入门 行业动态 更新时间:2024-10-23 12:33:25
本文介绍了WPF将MouseDown和TouchDown组合到同一事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在开发一款可在带触摸屏的笔记本电脑上使用的应用程序.因此,MouseDown事件本质上是在执行相同的操作,该怎么做.

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.

我写的代码是这样的-

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.

推荐答案

使eventArgs更通用.使用EventArgs代替MouseEventArgs和TouchEventArgs.

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

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

现在您可以从XAML挂接到同一事件:

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.

委托可以与参数类型为 是委托签名参数类型的基本类型.和 相反,您可以使用一个事件处理程序来代替单独的事件处理程序 处理程序.例如,您可以创建一个事件处理程序,该事件处理程序接受一个 EventArgs输入参数,并将其与Button.MouseClick事件一起使用 发送MouseEventArgs类型作为参数,并带有 发送一个KeyEventArgs参数的TextBox.KeyDown事件.

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.

更多推荐

WPF将MouseDown和TouchDown组合到同一事件

本文发布于:2023-10-27 00:07:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531741.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   事件   WPF   MouseDown   TouchDown

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!