I'm attempting to implement this question: Closing TabItem by clicking middle button
However, the e.Source property of CloseCommandExecuted() returns a TabControl object. This cannot be used to determine which TabItem was clicked. e.OriginalSource returns the Grid that's defined just inside of the datatemplate. Finally, following the parents upward from original source never leads to a TabItem object.
How can I get the TabItem the user clicked on?
Edit: In my case I'm binding objects via the ItemsSource.
//Xaml for the Window
<Window.Resources>
<DataTemplate x:Key="closableTabTemplate">
<Border x:Name="testBorder">
<Grid>
<Grid.InputBindings>
<MouseBinding Command="ApplicationCommands.Close" Gesture="MiddleClick" />
</Grid.InputBindings>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid>
<TextBlock Text="{Binding Headertext}"></TextBlock>
</Grid>
</Grid>
</Border>
</DataTemplate>
</Window.Resources>
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Close" Executed="CloseCommandExecuted" CanExecute="CloseCommandCanExecute" />
</Window.CommandBindings>
<Grid>
<TabControl x:Name="MainTabControl" ItemTemplate="{StaticResource closableTabTemplate}" Margin="10">
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem">
<!--<Setter Property="Header" Value="{Binding ModelName}"/>-->
<Setter Property="Content" Value="{Binding Content}"/>
</Style>
</TabControl.ItemContainerStyle>
</TabControl>
</Grid>
The object I'm binding. It's a sample specific for this question
public class TabContent
{
public string Headertext { get; set; }
public FrameworkElement Content = null;
}
The main window code
public partial class MainWindow
{
public ObservableCollection<TabContent> MyCollection = new ObservableCollection<TabContent>();
public MainWindow()
{
MyCollection.Add(new TabContent { Headertext = "item1" });
MyCollection.Add(new TabContent { Headertext = "item2" });
MyCollection.Add(new TabContent { Headertext = "item3" });
InitializeComponent();
MainTabControl.ItemsSource = MyCollection;
MainTabControl.SelectedIndex = 0;
}
private void CloseCommandExecuted(object sender, ExecutedRoutedEventArgs e)
{
//Need some way to access the tab item or item bound to tab item
//if (tabitem != null)
//{
// //MainTabControl.Items.Remove(tabitem);
//}
}
private void CloseCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
}