Share via


Events

Just a brief post with a code snippet demonstrating how to create a custom event with WPF... for most this won't be unfamiliar, but for those who are new to UI development, this is key...

Below is the snippet where I register the event. In this example, I have a Save button in a user control (called 'MyUserControl'), and the click of that Save button needs to be heard in the parent window. The event is called 'SaveButtonClickedEvent'...

public

static readonly RoutedEvent SaveButtonClickedEvent = EventManager.RegisterRoutedEvent("SaveButtonClicked", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyUserControl));

I now expose my custom event so I can add a handler in the main window...

public

event RoutedEventHandler SaveButtonClicked {

add { AddHandler(SaveButtonClickedEvent, value); }

remove { RemoveHandler(SaveButtonClickedEvent, value); }

}

Now, when the saved button in the user control is actually clicked I use the following line of code to raise the event up to the parent...

RaiseEvent(

new RoutedEventArgs(MyUserControl.SaveButtonClickedEvent, some_args_here));

... where 'some_args_here' can be any value or object.

Finally, I can add a listenter for the event in my main window with the following lines...

MyUserControl

myUserControl = new MyUserControl();

myUserControl.SaveButtonClicked += new RoutedEventHandler(MyUserControl_SaveButtonClicked);

Simple. The 'some_args_here' object can then be found in the event args under e.OriginalSource.

Martin

Comments

  • Anonymous
    August 01, 2007
    Nice.. What is the diference from a "regular" .NET events?