A button's click event is fired when a user click this control. But this event can be fired by code , for example :
myButton_Click(myButton, EventArgs.Empty)
How can I distinguish these 2 cases ?
Thank you !
A button's click event is fired when a user click this control. But this event can be fired by code , for example :
myButton_Click(myButton, EventArgs.Empty)
How can I distinguish these 2 cases ?
Thank you !
Create a new class that derives from RoutedEventArgs and pass that when you call the handler.
public class MyExtendedRoutedEventArgs : RoutedEventArgs
{
public bool ICalled {set;get;}
}
MyButton_Click(MyButton, new ExtendedRoutedEventArgs(){ICalled=true});
private void MyButton_Click(object sender, RoutedEventArgs e)
{
if(e.getType() == typeof(MyExtendedRoutedEventArgs)
{
//you called it
}
}
As written, short of examining the stack trace via reflection you are probably out of luck.
Now you /could/ refactor it by creating a new sub that does the actual work with an extra parameter that will tell you how it was pressed. The event handler can call the new sub and pass a value that says it was fired via event, and the other "manual" call can pass a value that says it was called by your code. The new sub can then look at the value and take whatever action it needs to.
Pass something else as the sender or args when you call it programmatically.
enter code here
myButton_Click("I called it",null);
myButton_Click(object sender, RoutedEventArgs e)
{
//Check the value of sender here
if(sender.ToString() == "I called it" )
{
//You know you called it
}
}
Would't it be easier to create a method that does the work, and call it from the Click
event and/or from anywhere else in the code?
Private Sub DoTheThing(ByVal calledFromCode as boolean, ByVal sender as object)
'Do the work here
End Sub
Private Sub myButton_Click(ByVal sender As Object, ByVal e As EventArgs)
DoTheThing(false, sender)
End Sub
Private Sub SomeOtherMethod()
DoTheThing(true, myButton)
End Sub