我有以下代碼。附加行爲中的匿名事件處理程序是否會導致泄漏?
所以基本上它會在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