Dragging over a dragablz:TabablzControl tab to bring it to front

时间:2018-12-19 11:24:20

标签: c# wpf drag-and-drop tabitem

I would like to implement a DragEnter-Event for each TabItem of my dragablz:TabablzControl. Tabs should be automatically selected when dragging a file over it.

I found two topics on stackoverflow that seem to be similar to my question:

Unfortunately these solutions doesn't work for TabablzControl from Dragablz.

<dragablz:TabablzControl Name="TC_FooBar" FixedHeaderCount="3">
      <TabItem Header="FIRST">
            <!-- <ContentOfFirstTabItem/> -->
      </TabItem>
      <TabItem Header="SECOND">
            <!-- <ContentOfSecondTabItem/> -->
      </TabItem>
      <TabItem Header="THIRD">
            <!-- <ContentOfThirdTabItem/> -->
      </TabItem>
</dragablz:TabablzControl>

What I have tried so far:

  • Implementing DragEnter und PreviewDragEnter events for each TabItem and for the TabablzControl itself.
  • Setting AllowDrop="True" for TabablzControl and each TabItem.

Everytime the e.Source is equal to the content of the currently selected tab. I'm not able to identify the correct TabItem. Any ideas?

1 个答案:

答案 0 :(得分:1)

这很容易。

您已经准备好正确的设置:

<dragablz:TabablzControl DragEnter="TabControl_OnDragEnter" AllowDrop="True">
    <TabItem Header="FIRST"/>
    <TabItem Header="SECOND"/>
    <TabItem Header="THIRD"/>
</dragablz:TabablzControl>

AllowDroptrue,并且有一个DragEnter路由事件处理程序。请注意,这是一个冒泡事件,但是您也可以使用隧道PreviewDragEnter版本。

魔术将在事件处理程序中发生。我们需要OriginalSource属性。但是,这将是一些Visual代表TabItem,而不是TabItem本身!您应该阅读有关WPF的样式和模板功能,以获取有关它的更多信息。 我们所需要做的就是从代表Visual的那个到实际的TabItem。我们可以通过走到视觉树上直到找到该项目来完成它:

private void TabControl_OnDragEnter(object sender, DragEventArgs e)
{
    // Just a sanity check - we need a Visual here
    if (!(e.OriginalSource is Visual v))
    {
        return;
    }

    // DragablzItems will represent our TabItems, so we search for those
    var item = GetParentOfType<DragablzItem>(v);

    // DragablzItem.Content should contain our original TabItem
    if (item != null && item.Content is TabItem ti)
    {
        ti.IsSelected = true;
    }
}

助手GetParentOfType方法可能如下所示:

static T GetParentOfType<T>(Visual visual) where T : Visual
{
    DependencyObject parent = visual;
    do
    {
        parent = VisualTreeHelper.GetParent(parent);
    } while (parent != null && !(parent is T));

    return parent as T;
}