There is a tabcontrol (tab), it has a close button, but when you add draganddrob (dragging tabs) like in the browser, the button stops working. where is the mistake? Here is the xml code

 <TabControl x:Name="TabCtrl" > <TabControl.Resources> <Style TargetType="TabItem"> <Setter Property="AllowDrop" Value="True"/> <EventSetter Event="PreviewMouseMove" Handler="TabItem_Drag"/> <EventSetter Event="Drop" Handler="TabItem_Drop"/> </Style> </TabControl.Resources> <TabItem Header="Tab1"> <TabItem.HeaderTemplate> <DataTemplate> <StackPanel> <TextBlock Text="TabItem 1" /> <Button Content="Close" Click="ButtonBase_OnClick" /> </StackPanel> </DataTemplate> </TabItem.HeaderTemplate> <Grid> <Label Content="TabItem 1"></Label> </Grid> </TabItem> <TabItem Header="Tab2"> <TabItem.HeaderTemplate> <DataTemplate> <StackPanel> <TextBlock Text="TabItem 2" /> <Button Content="Close" Click="ButtonBase_OnClick" /> </StackPanel> </DataTemplate> </TabItem.HeaderTemplate> <Grid> <Label Content="TabItem 2"></Label> </Grid> </TabItem> </TabControl> </Window> 

C #

  private void ButtonBase_DoubleClick(object sender, RoutedEventArgs e) { TabCtrl.Items.RemoveAt(TabCtrl.SelectedIndex); } private TabItem GetTargetTabItem(object originalSource) { var current = originalSource as DependencyObject; while (current != null) { var tabItem = current as TabItem; if (tabItem != null) { return tabItem; } current = VisualTreeHelper.GetParent(current); } return null; } private void TabItem_Drag(object sender, MouseEventArgs e) { var tabItem = e.Source as TabItem; if (tabItem == null) return; if (Mouse.PrimaryDevice.LeftButton == MouseButtonState.Pressed) DragDrop.DoDragDrop(tabItem, tabItem, DragDropEffects.All); } private void TabItem_Drop(object sender, DragEventArgs e) { var tabItemTarget = GetTargetTabItem(e.OriginalSource); if (tabItemTarget != null) { var tabItemSource = (TabItem)e.Data.GetData(typeof(TabItem)); if (tabItemTarget != tabItemSource) { int sourceIndex = TabCtrl.Items.IndexOf(tabItemSource); int targetIndex = TabCtrl.Items.IndexOf(tabItemTarget); TabCtrl.Items.Remove(tabItemSource); TabCtrl.Items.Insert(targetIndex, tabItemSource); TabCtrl.Items.Remove(tabItemTarget); TabCtrl.Items.Insert(sourceIndex, tabItemTarget); TabCtrl.SelectedIndex = targetIndex; } } } 

    1 answer 1

    I decided myself, if suddenly someone has the same problem. the point was that he was dragging and the button was processed with one click event and therefore he did not understand. he solved the problem by deleting it by double-clicking MouseDoubleClick