我有以下代码。
所以基本上它在引发事件DelegateCommand
时执行命令(基于弱引用委托) 。Selector.SelectionChanged
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);
}
请注意,上下文是静态的。
这会导致泄漏吗?我可以猜测它不会,因为据我所知,匿名处理程序将一直有效,直到所有“外部”变量(即selector
此处command
)的范围不适用于 GC。一旦它们被 GCed,当View
(that has selector
) 和ViewModel
(that issupping command
) 从父 GUI 卸载时,匿名委托也将被取消挂钩。
我在这里吗?