Dot-Net

重新排序 WPF TabControl 中的選項卡

  • October 18, 2019

有沒有一種簡單的方法來自定義 WPF TabControl 以便它支持 TabItem 拖放 - 類似於 IE 和 firefox 所做的。

您可以使用或開始使用Bea Stollnitz現有的用於在 ItemsControl 中拖放的幫助器。正如她所提到的,它確實有一些限制,但它是一個很好的起點,並且可能會按原樣執行您需要的大多數功能。

導入她的 DragDropHelper 和 Adorner 類後,將它們與TabControl一起使用非常簡單(因為它是 ItemsControl 的後代)。

設置一個簡單的拖動模板,TabControl 上的屬性就是我們所需要的。由於該解決方案設置為處理數據綁定項的拖動,如果您的選項卡是在 XAML 中靜態聲明的,而不是使用 TabControl.ItemsSource,那麼您可以將它們的 DataContext 綁定到它們自己。

<Window x:Class="Samples.Window1"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:dd="clr-namespace:DragDropListBox"
   Title="Dragging TabItems"
   Height="300"
   Width="300">

<Window.Resources>
   <DataTemplate x:Key="Local_TabItemDragTemplate">
       <Border CornerRadius="5"
               BorderBrush="Black"
               BorderThickness="2"
               Background="DodgerBlue">
           <TextBlock Margin="5"
                      Text="{Binding Path=Header}" />
       </Border>
   </DataTemplate>
</Window.Resources>

<StackPanel>
   <TabControl dd:DragDropHelper.IsDragSource="true"
               dd:DragDropHelper.IsDropTarget="true"
               dd:DragDropHelper.DragDropTemplate="{StaticResource Local_TabItemDragTemplate}">
       <TabControl.ItemContainerStyle>
           <Style TargetType="{x:Type TabItem}">
               <Setter Property="DataContext"
                       Value="{Binding RelativeSource={RelativeSource Self}}" />
           </Style>
       </TabControl.ItemContainerStyle>
       <TabItem Header="Tab 1" />
       <TabItem Header="Tab 2" />
       <TabItem Header="Tab 3" />
       <TabItem Header="Tab 4" />
   </TabControl>
   <TabControl dd:DragDropHelper.IsDragSource="true"
               dd:DragDropHelper.IsDropTarget="true"
               dd:DragDropHelper.DragDropTemplate="{StaticResource Local_TabItemDragTemplate}">
       <TabControl.ItemContainerStyle>
           <Style TargetType="{x:Type TabItem}">
               <Setter Property="DataContext"
                       Value="{Binding RelativeSource={RelativeSource Self}}" />
           </Style>
       </TabControl.ItemContainerStyle>
       <TabItem Header="Tab 5" />
       <TabItem Header="Tab 6" />
       <TabItem Header="Tab 7" />
       <TabItem Header="Tab 8" />
   </TabControl>
</StackPanel>

替代文字

引用自:https://stackoverflow.com/questions/1093571