WPF combining MouseDown and TouchDown to same event

蓝咒 提交于 2019-11-29 10:57:51

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!