You cannot "make an event", because this event instance already exist in each instance of the class
Button
. It is called
Button.Click
. You don't need to "make" it,
you need to handle it. That means: adding an event handling to an invocation list of an event instance, which is the instance (not-static) event member of the class
Button
:
Button.Click
. The handler is added using the += operator. Equivalent thing can be done in XAML, using the designer or not. The XAML sample can be found here:
https://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.buttonbase.click%28v=vs.110%29.aspx[
^].
If you do it in code, the syntax is
myButton.Click += MyClickHander;
void MyClickHander(Object sender, RoutedEventArgs e) {
}
Please see:
https://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.buttonbase.click%28v=vs.110%29.aspx[
^],
https://msdn.microsoft.com/en-us/library/system.windows.routedeventhandler%28v=vs.110%29.aspx[
^],
https://msdn.microsoft.com/en-us/library/system.windows.routedeventargs%28v=vs.110%29.aspx[
^].
Note 1: Event mechanism in WPF is very special (
https://msdn.microsoft.com/en-us/library/ms753115%28v=vs.110%29.aspx[
^]), but in the simple cases we are discussing you don't need to understand anything specific to WPF, it will be enough just follow the patter used for all event handling used in .NET.
Note 2: Some developers may say that my first line in my code sample on top is wrong, because new
new RoutedEventHandler(MyClickHander)
instead of just
MyClickHander
.
Don't trust them; this is not needed. This "new" is a bogus which probably stems from the imperfections of some Microsoft documentation. This exactly the same kind of bogus as
int a = new int();
absolutely redundant construct with correct syntax.
But I use even simpler approach which does not even require knowing the event argument types (in such simple cases). This is done with the use of
anonymous methods, especially in
lambda syntax:
myButton.Click += (sender, eventArgs) => { SomeCodeHandlingThisEvent(); }
Even if you need to use code specific the particular
eventArgs
type (this is needed, for example, when you need to get mouse coordinates, and in many other cases), you don't need to write its type, which is
inferred through the mechanism of
type inference.
—SA