0

I have a WPF UserControl that is added as Content in a TabItem. The TabItem is added to the Items collection of TabControl. The Header of the TabItem contains one Label and one Button. The button click removes the TabItem from the Items collection of TabControl. So the reference of UserControl is not there anymore. I have some clean up code to be run for the UserControl when the TabItem is removed.

I was looking for Dispose method in the UserControl, but there is no such method available for overriding.

Also, I tried to use Dispatcher.ShutdownStarted Event, but that also doesn't work.

Brij
  • 11,731
  • 22
  • 78
  • 116

1 Answers1

1

You could extend UserControl and add a method to clean up your control. You can call this method from where ever you remove the TabItem from the TabControl from:

private void Button_Click(object sender, RoutedEventArgs e)
{
    ExtendedUserControl control = (ExtendedUserControl)tabItem.Content;
    control.CleanUp();
    tabControl.Items.Remove(tabItem);
}

Alternatively, you could add the clean up method to your data class that is data bound to the UserControl:

private void Button_Click(object sender, RoutedEventArgs e)
{
    UserControl control = (UserControl)tabItem.Content;
    YourDataClass data = (YourDataClass)control.DataContext;
    data.CleanUp();
    tabControl.Items.Remove(tabItem);
}
Sheridan
  • 68,826
  • 24
  • 143
  • 183