Passing variable with RoutedEventArgs?
Create a new subclass of RoutedEventArgs
, add a property to it where you can store the variable to be passed and create a respective handler delegate of type void (object, YourNewEventArgs)
which you then assign as the handler type of your event (which currently uses a normal RoutedEventHandler
which hence only provides normal RoutedEventArgs
).
If the event then is to be raised you need to create your new event args and pass the variable to its property for that variable. How to get the value in the handler should be self-explanatory.
I needed something similar and with the help of both @Arya and @H.B. I came up with this:
My custom RoutedEventArgs subclass
public class ChangePageEventArgs : RoutedEventArgs {
private readonly int _pageNumber;
public int PageNumber {
get { return _pageNumber; }
}
public ChangePageEventArgs(RoutedEvent routedEvent, int pageNumber) : base(routedEvent) {
this._pageNumber = pageNumber;
}
}
My child class
private void defineButton_Click(object sender, RoutedEventArgs e) {
ChangePageItemList(2);
}
public static readonly RoutedEvent GoToItemPropertiesViewEvent = EventManager.RegisterRoutedEvent(
"GoToItemPropertiesView", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(NoObjectView));
// Provide CLR accessors for the event
public event RoutedEventHandler GoToItemPropertiesView {
add { AddHandler(GoToItemPropertiesViewEvent, value); }
remove { RemoveHandler(GoToItemPropertiesViewEvent, value); }
}
public void ChangePageItemList(int _pageNumber) {
ChangePageEventArgs args = new ChangePageEventArgs(GoToItemPropertiesViewEvent, _pageNumber);
this.RaiseEvent(args);
}
My parent class
private ItemListView createItemListView() {
_itemListView = new ItemListView();
_itemListView.GoToItemPropertiesView += new RoutedEventHandler(ChangePage);
return _itemListView;
}
private void ChangePage(object sender, RoutedEventArgs e) {
ChangePageEventArgs args = (ChangePageEventArgs)e;
// Value of page number is 2
int _pageNumber = args.PageNumber;
}
Hope it helps you @Arya