private static FrameworkElement CreateTabHeader(TabItem tabItem, bool closeViewModelOnUnload) { Argument.IsNotNull("tabItem", tabItem); var stackPanel = new StackPanel(); stackPanel.Orientation = Orientation.Horizontal; var titleLabel = new Label(); titleLabel.Content = string.Format("Close on unload: {0}", closeViewModelOnUnload); stackPanel.Children.Add(titleLabel); var closeButton = new Button(); closeButton.Content = "X"; closeButton.ToolTip = "Close"; closeButton.Click += (sender, e) => { var tabControl = tabItem.FindLogicalAncestorByType<System.Windows.Controls.TabControl>(); if (tabControl != null) { var tabItemAsIUserControl = tabItem.Content as IUserControl; if ((tabItemAsIUserControl != null) && (tabItemAsIUserControl.ViewModel != null)) { tabItemAsIUserControl.ViewModel.CloseViewModel(false); } tabControl.Items.Remove(tabItem); } }; stackPanel.Children.Add(closeButton); return stackPanel; }