开发者

Unsubscribing events in WPF Control

I have a custom control, a range slider, which is used in one of my views.

The constructor looks like this:

开发者_StackOverflow中文版
        EventHandler ReCalculateWidthsHandler;
        public RangeSlider()
        {
            ReCalculateWidthsHandler = OnReCalculateWidths;
            DependencyPropertyDescriptor.FromProperty(ActualWidthProperty, typeof(RangeSlider)).
                AddValueChanged(this, ReCalculateWidthsHandler);
        }

I do not know when/how I can unscubscribe that event handler. There is no Dispose method in Control. Is there any way I can be notified that the control is being disposed/removed so that I can unsubscribe any subscribed events?

This can be a more general question: Given a custom control that extends Control, how can you tell when it is disposed?

Thank you.


Usually, you should use OverrideMetadata to add change handler for dependency property. Unfortunately it doesn't work for read only properties. That's why you use property descriptor I think. You know this way is too complicated because AddValueChanged stores static strong reference which cause memory leak. I think you should call ReCalculateWidthsHandler from the SizeChanged event instead of subscribing to property descriptor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜