The following code shows a normal event and a routed event. Here I have used the same event name for explaining purposes but in reality I am using just the routed event.
//Normal Event
public event SelectedHandler Selected;
public delegate void SelectedHandler(Object Sender, RoutedEventArgs e);
//Routed Event
public static readonly RoutedEvent SelectedEvent =
EventManager.RegisterRoutedEvent(
"Selected", RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
typeof(MyUserControl));
//add remove handlers
public event RoutedEventHandler Selected
{
add { AddHandler(SelectedEvent, value); }
remove { RemoveHandler(SelectedEvent, value); }
}
I am raising these events from a couple of event handlers as follows
private void lstvMyView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//Normal Event Raise
if (Selected != null)
Selected(this, e);
//Routed Event Raise
RoutedEventArgs args = new RoutedEventArgs(SelectedEvent);
RaiseEvent(args);
}
private void lstvMyView_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
//Normal Event Raise
if (Selected != null)
Selected(this, e);
//Routed Event Raise
RoutedEventArgs args = new RoutedEventArgs(SelectedEvent);
RaiseEvent(args);
}
When I am handling the normal Event I am able to send the args of both the handlers to the event but in Routed Event the args will be a new instance. I want to pass the args of both the handlers to the Routed Event. Is it possible to achieve this? If yes then how?
first of all you do not need this (and should remove it):
i.e. you do not need to define a separate “normal” event, because you have already done it with this declaration:
with the above code block you are “wrapping” the routed event with a “normal” (clr) one so the users of your class can use it with the “normal” syntax (i.e.
instanceOfMyUserControl.Selected += ....)second, if you want the event arguments of your routed event to be the same as the ones of the
SelectionChangedevent of the theListViewyou are listening to, you should declare your routed event this way:Notice that I have substituted the
RoutedEventHandlerwithSelectionChangedEventHandler, as it is the predefined one that can “carry”SelectionChangedEventArgs.Now for the rising of the event.
You do not need to rise both the “normal” and the routed one (as the “normal” is a wrapper for the routed), so you should delete this:
and rise only the routed version, which can be done this way:
Notice that I am using the event arguments from the original event to set the
AddedItemsandRemovedItemsof the one custom one.