移動可能な 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 値を使用しているためです。