Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to rearrange tab items in tab control in wpf?

Is it possible to rearrange tab items in tab control in run time? For example I have 3 tab items which are about cars and 4 tabs about house. I want to be able to rearrange them using drag and drop. Is it possible or it is something fantastic?

I have Tab Control here is XAML.

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

Tab items will be added in runtime. Thanks for helping me!

like image 289
Firdavs Kurbonov Avatar asked May 24 '12 13:05

Firdavs Kurbonov


1 Answers

found a solution in the MSDN forum.

Here is the link:

DragDrop TabItem

Here is the solution:

C# solution

WPF code:

<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>

C# code behind:

private void TabItem_PreviewMouseMove(object sender, MouseEventArgs e)
{
    if (!(e.Source is TabItem tabItem))
    {
        return;
    }

    if (Mouse.PrimaryDevice.LeftButton == MouseButtonState.Pressed)
    {
        DragDrop.DoDragDrop(tabItem, tabItem, DragDropEffects.All);
    }
}

private void TabItem_Drop(object sender, DragEventArgs e)
{
    if (e.Source is TabItem tabItemTarget &&
        e.Data.GetData(typeof(TabItem)) is TabItem tabItemSource &&
        !tabItemTarget.Equals(tabItemSource) &&
        tabItemTarget.Parent is TabControl tabControl)
    {
        int targetIndex = tabControl.Items.IndexOf(tabItemTarget);

        tabControl.Items.Remove(tabItemSource);
        tabControl.Items.Insert(targetIndex, tabItemSource);
        tabItemSource.IsSelected = true;
    }
}
like image 171
csteinmueller Avatar answered Sep 30 '22 01:09

csteinmueller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!