WPF将MouseDown和TouchDown组合到同一事件 [英] WPF combining MouseDown and TouchDown to same event

查看:1082
本文介绍了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代替MouseEventArgsTouchEventArgs.

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组合到同一事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆