Wednesday, April 6, 2011

Event in WinForm and WPF

Event is a member that enables a class to provide notification.

I. Review event in WinForm


Let's review event concept WinForm(or console, or Asp.net or any application which doesn't reference Presentation.Core assembly to support the concept of routed event) first:

1. EventHandler is a predefined delegate, it is the same as we define a delegate:

public delegate void Del(object,EventArgs);

It is also the same as Action< object, EventArgs>

EventHandler requires an object and an EventArgs as parameter.

2. We can define a custom event use any delegate type:

for example,we created a class called ExtendedButton:

public delegate void Del(int i);
public class ExtendedButton:System.Windows.Forms.Button
{
public event Del ValueSetted;
public event EventHandler Pushed;
public event Action MyMouseEntered;
}
3. Subscribe to the EventHandler Can also use Lambda Expression

for example:


ExtensionButton extbtn=new ExtensionButton();
extbtn.Pushed+=new EventHandler(myMethod);

public void myMethod(object s, EventArgs e)
{
//...Some code
}

We can also write:
extbtn.Pushed+=(s,e)=>//...Some code

4. Is event keyword optional?

The keyword event is important. Without event keyword, the member in the class will be treated as a field which is delegate type. for example the above code, we get the event keyword off:

public delegate void Del(int i);
public class ExtendedButton:System.Windows.Forms.Button
{
public Del ValueSetted;
public EventHandler Pushed;
public Action MyMouseEntered;
}

Then we can write code like this way:

ExtensionButton extbtn=new ExtensionButton();
extbtn.ValueSetted(5);
extbtn.Pushed(s,e);
extbtn.MyMousedEventered();

But when we add the keyword event, this make sure the event cannot be called outside of the owner class. Then this kind of call like extbtn.ValueSetted(5) will have compile error. The error message will be like:
"The event '' can only appear on the left side of += or -= (excepted used within the class '')"

5. How to invoke event outside of the Owner class?

We can add a method to the ExtensionButton class, for instance:
public class ExtendedButton:System.Windows.Forms.Button
{
public EventHandler Pushed;

public void RaisePushed()
{
if (Pushed != null)
Pushed(this, EventArgs.Empty);
}
}

Now we can invoke the event by:

ExtensionButton extbtn=new ExtensionButton();
extbtn.RaisePushed();

I have written the sample code here.

For C# 4.0, event mechanism for cross thread/synchronization is re written, see this
Link.



II. Event in WPF


WPF introduced routed events, which can be raised by multiple controls and handled by multiple handlers.

There are three type of routed events:
Direct Event
Bubbling Event
Tunneling Event

No comments: