WPF user control not being disposed

2019-07-21 04:13发布

问题:

Each time I open a view the number of get requests to each of the model properties increment by one. Just to be clear if I open the view once, close it and open it again there are two get requests to each property, and if the property is set and RaisePropertyChanged("propertName") is triggered there are two get requests again. The number of get requests is always equal to the number of times the view has been instantiated! I have debugged the life out of this issue and everything points towards it being that the user controls aren't being disposed of when the view is closed and the bindings are withheld.

What should I do to deal with this? I have looked into disposal of user controls however I have been unsuccessful in finding something to help me fix this. Maybe I am not looking for the right topic? Any help or pointers would be greatly appreciated - thanks!

回答1:

WPF controls do not implement IDisposable and, hence, don't need to be disposed of. I believe that you want to say "is not being marked as eligible to garbage collection"

it seems that your problem is related to what is called an event reference. Some of your living instance (some class you have which is not your window/user control) retains a reference to an event. if if you close the Window or UserControl that link still lives on and it is not cleared automatically.

When closing the window/user control you should dereference your event like this

EventName-= methodHandler or this.UserControlInstance=null

You may read some interesting pattern here