0

我想创建可移动的 TabItems。但是当我删除项目时,它会因为索引超出数组区域而崩溃。

请告诉我我的错误
代码:

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

代码背后:

 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);
        }
    }

//编辑:我的 SelectionChanged 事件让程序崩溃。但我需要它,否则我的整个程序将无法运行。崩溃的原因是我使用了 TabControl 的 SelectedIndex 值,当时是未定义的

4

0 回答 0