Subscription to CanExecuteChanged lost

Topics: Prism v2 - WPF 3.5
May 5, 2010 at 5:07 PM

Hi there,

I'm building a custom WPF control that exposes a read/write DelegateCommand<T> property as follows.
This is done so that I could bind an actual command instance defined in my view model to this control.
Note that I'm subscribing to  SearchCommand.CanExecuteChanged inside OnSearchCommandChanged. However, at some point the event handler stops being called.

I've looked at the command's _canExecuteChangedHandlers still has a WeakReference to my handler method, however its Target quickly becomes null. I'm not really sure why the reference gets lost since the WPF control is never removed from the visual tree.

Please advise.

        public DelegateCommand<IList<FilterCriterion>> SearchCommand
            get { return (DelegateCommand<IList<FilterCriterion>>)GetValue(SearchCommandProperty); }
            set { SetValue(SearchCommandProperty, value); }

        public static readonly DependencyProperty SearchCommandProperty =
            DependencyProperty.Register("SearchCommand", typeof(DelegateCommand<IList<FilterCriterion>>), typeof(AdvancedFilter), new UIPropertyMetadata(null, OnSearchCommandChanged));

        private static void OnSearchCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
            AdvancedFilter advancedFilter = (AdvancedFilter)d;
            var oldSearchCommand = e.OldValue as DelegateCommand<IList<FilterCriterion>>;
            if (oldSearchCommand != null)
                oldSearchCommand.CanExecuteChanged -= advancedFilter._searchCommand_CanExecuteChanged;
            var newSearchCommand = e.NewValue as DelegateCommand<IList<FilterCriterion>>;
            if (newSearchCommand != null)
                newSearchCommand.CanExecuteChanged += advancedFilter._searchCommand_CanExecuteChanged;

        void _searchCommand_CanExecuteChanged(object sender, EventArgs e)
            // my custom code (removed here)

May 5, 2010 at 5:21 PM

Nevermind, guys, I've just read the XML comments on 


Apparently I have to keep a reference to the EventHandler.