When you are adding and removing event handlers and you want to have additional parameters, how do you go about doing this? The below code is like something i would want but obviously does not work.
How would you go about this? – it’s troublesome that i cant use delegates or lambdas as i need to also remove the handler.
private static void IsDefaultChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
{
if ((bool)args.NewValue)
{
Window.Current.CoreWindow.KeyUp += CoreWindowOnKeyUp(dependencyObject);
}
else
{
Window.Current.CoreWindow.KeyUp -= CoreWindowOnKeyUp(dependencyObject);
}
}
private static void CoreWindowOnKeyUp(CoreWindow sender, KeyEventArgs args, DependencyObject dependencyObject)
{
((ICommand)dependencyObject.GetValue(Button.CommandProperty)).Execute(null);
}
What you can do is:
DependencyObjects that you add to/remove from in yourIsDefaultChangedmethod.CoreWindowOnKeyUphandler so it only accepts the expected two parameters, and queries the collection ofDependencyObjects itself. Bind this event once and don’t unbind it.I.e. rather than having an event with a handler for each current dependency object, you have an event with a single handler that queries a collection for current dependency objects.
Alternatively, if Richard’s code doesn’t unbind lambdas properly, you can keep a
Dictionary<DependencyObject, EventHandler>so you can retrieve the exact lambda that was bound and unbind it accordingly.