Reputation: 7903
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.
The code I have written something like this -
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.
Upvotes: 5
Views: 10770
Reputation: 81253
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.
Upvotes: 14