我正在开发一款可在带触摸屏的笔记本电脑上使用的应用程序.因此,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组合到同一事件
发布评论