我有以下代码。附加行为中的匿名事件处理程序是否会导致泄漏?
所以基本上它会在Selector.SelectionChanged
事件发生时执行基于弱参考代表的命令(DelegateCommand
)。
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
(其具有selector
)和ViewModel
(即提供command
)从父GUI被卸载时将发生,则匿名委托也将被解除挂钩。
我在这儿吗?
奇妙的答案。是的,我确保加载'ICommand'的模式只有一次,即没有理由为什么需要为属性更改通知。我的'ViewModel'中包含该命令的私有变量是'readonly',并在创建VM实例时加载。另外,命令本身为'CanExecute'和'Execute'实现弱委托。 –
在那种情况下,你应该很好去:) – Lukazoid