简体   繁体   English

我应该在监听 DependencyProperty 更改时使用弱事件监听器吗?

[英]Should I use weak event listeners while listening to DependencyProperty changes?

I was looking in the framework for an implementation of WeakEventManager that listens for changes to DependencyProperties.我在框架中寻找一个WeakEventManager的实现,它监听对 DependencyProperties 的更改。 I'm a bit confused by the fact that the only weak property change event listener I find, the PropertyChangedEventManager , is designed to be used on types that implement INotifyPropertyChanged.我发现唯一的弱属性更改事件侦听器PropertyChangedEventManager被设计用于实现 INotifyPropertyChanged 的类型,这让我有点困惑。

Does this mean that if you listen to a DependencyProperty for changes这是否意味着如果您听 DependencyProperty 进行更改

DependencyPropertyDescriptor
    .FromProperty(target, target.OwnerType)
    .AddValueChanged(component, handler)

that I don't have to worry about leaking instances who are kept alive by event registration?我不必担心通过事件注册保持活动状态的泄漏实例?

DependencyPropertyDescriptor leaks big time, I had lot of issues because of it. DependencyPropertyDescriptor大量泄漏,因此我遇到了很多问题。 Unless you explicitly call RemoveValueChanged all your components will be rooted.除非您明确调用RemoveValueChanged ,否则您的所有组件都将被植根。 Internally it maintains a HashTable of EventHandler .它在内部维护一个EventHandlerHashTable Here is what it does:这是它的作用:

if (this.valueChangedHandlers == null)
  this.valueChangedHandlers = new Hashtable();
EventHandler eventHandler = (EventHandler) this.valueChangedHandlers[component];
this.valueChangedHandlers[component] = (object) Delegate.Combine((Delegate) eventHandler, (Delegate) handler);

Since property descriptors are cached, all your components will be rooted.由于缓存了属性描述符,因此您的所有组件都将被植根。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM