2012-05-24 24 views
9

Có thể sắp xếp lại các mục tab trong điều khiển tab trong thời gian chạy không? Ví dụ tôi có 3 mục tab về xe hơi và 4 tab về nhà. Tôi muốn có thể sắp xếp lại chúng bằng cách kéo và thả. Có thể hay nó là một cái gì đó tuyệt vời?Có thể sắp xếp lại các mục tab trong điều khiển tab trong wpf không?

Tôi có Tab Control ở đây là XAML.

<TabControl x:Name="tc" Visibility="Collapsed" GotFocus="Focus" AllowDrop="True" > 
      </TabControl> 

Các mục tab sẽ được thêm vào trong thời gian chạy. Cảm ơn bạn đã giúp tôi!

Trả lời

19

tìm thấy giải pháp trong diễn đàn MSDN.

Dưới đây là liên kết:

DragDrop TabItem

Dưới đây là giải pháp:

C# giải pháp mã

WPF:

<TabControl> 
    <TabControl.Resources> 
     <Style TargetType="TabItem"> 
      <Setter Property="AllowDrop" Value="True"/> 
       <EventSetter Event="PreviewMouseMove" Handler="TabItem_PreviewMouseMove"/> 
       <EventSetter Event="Drop" Handler="TabItem_Drop"/> 
     </Style> 
    </TabControl.Resources> 

    <TabItem Header="Tabitem 1"/> 
    <TabItem Header="Tabitem 2"/> 
    <TabItem Header="Tabitem 3"/> 
    <TabItem Header="Tabitem 4"/> 
    <TabItem Header="Tabitem 5"/> 
</TabControl> 

Mã C# đằng sau:

private void TabItem_PreviewMouseMove(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 = e.Source as TabItem; 

    var tabItemSource = e.Data.GetData(typeof(TabItem)) as TabItem; 

    if (!tabItemTarget.Equals(tabItemSource)) 
    { 
     var tabControl = tabItemTarget.Parent as TabControl; 
     int sourceIndex = tabControl.Items.IndexOf(tabItemSource); 
     int targetIndex = tabControl.Items.IndexOf(tabItemTarget); 

     tabControl.Items.Remove(tabItemSource); 
     tabControl.Items.Insert(targetIndex, tabItemSource); 

     tabControl.Items.Remove(tabItemTarget); 
     tabControl.Items.Insert(sourceIndex, tabItemTarget); 
    } 
} 
+0

Bạn có thể vui lòng cho tôi mã trong C#, nó sẽ được đánh giá cao. Cảm ơn bạn. –

+0

Mã hiện đang ở C#. Giải pháp này làm việc cho tôi. – csteinmueller

+0

Mã này hoạt động tốt khi Mục tab trống, nhưng mục tab của tôi có Điều khiển người dùng trong đó có nhiều yếu tố giao diện người dùng. Thậm chí tôi có thể đặt con trỏ vào TextBox, nó cho tôi lỗi. Nhấp chuột đang hoạt động trong từng yếu tố giao diện người dùng không phải là thứ tôi muốn. tôi hy vọng tôi có thể giải thích cho bạn. –