I have following code.
So basically it executes command (DelegateCommand
based on weak reference delegates), when Selector.SelectionChanged
event is raised.
public static readonly DependencyProperty SelectionCommandProperty
= DependencyProperty.RegisterAttached(
"SelectionCommand",
typeof(ICommand),
typeof(CommonUtilities),
new PropertyMetadata(null, OnSelectionCommandPropertyChanged));
private static void OnSelectionCommandPropertyChanged(
DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var selector = d as Selector;
var command = e.NewValue as ICommand;
if (selector != null && command != null)
{
selector.SelectionChanged
+= (o, args) => command.Execute(selector.SelectedItem);
}
}
public static ICommand GetSelectionCommand(DependencyObject d)
{
return d.GetValue(SelectionCommandProperty) as ICommand;
}
public static void SetSelectionCommand(DependencyObject d, ICommand value)
{
d.SetValue(SelectionCommandProperty, value);
}
Note that the context is static.
Does this cause leak? I can guess that it doesnt because as far as I know, the anonymous handler would be in effect until the scope of all "outer" variables (i.e. selector
, command
here) is not applicable for GC. Once they are GCed which would happen when the View
(that has selector
) and ViewModel
(that is supplying command
) are unloaded from parent GUI, the anonymous delegate would also be unhooked.
Am I right here?