ashlar64
ashlar64

Reputation: 1094

WPF UserControl that is a tab in a tabcontrol - how to detect if it is closing

I have a class that is inheriting from a UserControl. I am showing this class in a WPF TabControl as a tab. The tab has a small x and can be closed by clicking on it. I need a way to do some cleanup code before the tab is destroyed.

I don't believe I can use the Unloaded event to do this because the Unloaded event is called when the UserControl is being destroyed and it is also being called when you click on another tab.

Any ideas on how to deal with this situation?

EDIT: Here is more info. In my UserControl class I have a 3rd part control that I am using. Basically a graphing control. There are a couple lines of code I would like to run to ensure that there are no memory leaks. If you want to read more about it then this would be the web address that talks more about it:

http://support.scichart.com/index.php?/News/NewsItem/View/21/wpf-xname-memory-leak--how-to-clear-memory-in-scichart

Upvotes: 1

Views: 1007

Answers (1)

James Willock
James Willock

Reputation: 2037

You can have a look at the way I have done this in the dragablz TabControl on GitHub.

Essentially the TabControl listens to a RoutedCommend raised from the close button, then calls an optional callback which enables a MVVM view model (or old-style control type code) to dispose an associated view model, or perform any other tidy up code you want to do (or indeed cancel the close operation).

In the example project file on GitHub, look for ClosingItemHandlerImpl and work back from there.

http://github.com/ButchersBoy/Dragablz/blob/master/DragablzDemo/BoundExampleModel.cs

ClosingItemHandlerImpl is bound in from the XAML, and the tab control will call it prior to removing a tab.

Upvotes: 2

Related Questions