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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21399502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 10:37:39  来源:igfitidea点击:

WPF combining MouseDown and TouchDown to same event

c#wpftouchmouseevent

提问by Carbine

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.

我正在开发一个应用程序,它将在带触摸屏的笔记本电脑上使用。因此 MouseDown 事件本质上是在做同样的动作,这应该如何做。

The code I have written something like this -

我写的代码是这样的 -

XAML

XAML

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

C#

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.

有一个更好的方法吗?任何反馈表示赞赏。

回答by Rohit Vats

Make eventArgs to be more generic one. Use EventArgsin place of MouseEventArgsand TouchEventArgs.

使 eventArgs 更通用。使用EventArgs到位MouseEventArgsTouchEventArgs

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

and now you can hook to same event from XAML:

现在您可以从 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.

委托可以与具有委托签名参数类型的基类型类型参数的方法一起使用。通过逆变,您可以使用一个事件处理程序而不是单独的处理程序。例如,您可以创建一个接受 EventArgs 输入参数的事件处理程序,并将其与发送 MouseEventArgs 类型作为参数的 Button.MouseClick 事件以及发送 KeyEventArgs 参数的 TextBox.KeyDown 事件一起使用。