是否可以在 wpf 的选项卡控件中重新排列选项卡项?
问题描述:
是否可以在运行时重新排列选项卡控件中的选项卡项?例如,我有 3 个关于汽车的选项卡和 4 个关于房子的选项卡.我希望能够使用拖放重新排列它们.有可能吗,还是很棒的东西?
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?
我这里的 Tab Control 是 XAML.
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!
答
在 MSDN 论坛中找到了解决方案.
found a solution in the MSDN forum.
这是链接:
解决办法如下:
C# 解决方案
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>
背后的C#代码:
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;
}
}