且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF 从 Windows 资源管理器中将文件拖放到 TreeView 上

更新时间:2023-02-04 15:27:59

我认为问题在于您没有将项目拖到 TreeViewItems 本身上.这是必要的,因为您的事件仅为 TreeViewItems 注册.如果要拖放到树的父级别,则需要将相应的事件添加到树中.

I think the issue is you are not dragging the item over the TreeViewItems themselves. This is necessary because your events are registered for the TreeViewItems only. If you want to drag and drop into a parent level of you tree, you will need to add the corresponding events to your tree.

您在使用此解决方案时遇到的问题是 TreeView 事件将首先触发.所以现在你必须知道你结束了哪个节点才能正确添加它.有一些解决方案可以确定您在哪个节点上.但是,我建议向您的树中添加一个始终存在的***元素.然后像您一样将事件连接到 TreeViewItems.这样,您就可以在顶层添加,而无需处理 TreeView 事件,因为您可以拖动到该顶层项目.

The issue you will have with this solution is the TreeView events will fire first. So now you're going to have to know which node you're over to add it properly. There are solutions to figure out which node you are over. However, I would suggest adding a top level element to your tree that is always there. Then wire up the events to the TreeViewItems like you are. That way, you can add at a top level without having to handle the TreeView events because you can drag to that top level item.

下面是我用来测试它的内容,如果我直接拖到 TreeViewItems 上,我会看到断点.您可能不认识某些命名空间,但那是因为它引用了我的项目.

Below is what I used to test it out and I'm seeing the breakpoints if I drag directly over the TreeViewItems. You may not recognize some namespaces but that's because it's referencing my project.

XAML:

  <TreeView x:Name="treeView">
     <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}" >
           <Setter Property="TreeViewItem.AllowDrop" Value="True"/>
           <EventSetter Event="TreeViewItem.DragOver" Handler="treeView_DragOver" />
           <EventSetter Event="TreeViewItem.Drop" Handler="treeView_Drop" />
           <EventSetter Event="TreeViewItem.MouseMove" Handler="treeView_MouseMove" />
        </Style>
     </TreeView.ItemContainerStyle>

     <TreeView.Resources>
        <DataTemplate DataType="{x:Type FileExplorerDragDrop:TestClass}">
           <StackPanel Orientation="Vertical"  >
              <TextBlock Text="{Binding Path=Title}" />
              <TextBlock Text="{Binding Path=Url}" />
           </StackPanel>
        </DataTemplate>
     </TreeView.Resources>
  </TreeView>  

背后的代码:

  public MainWindow()
  {
     InitializeComponent();

     treeView.ItemsSource = new[] 
     { 
        new TestClass { Title = "Google", Url = "http://www.google.com" }, 
        new TestClass { Title = "Microsoft", Url = "http://www.microsoft.com" },
        new TestClass{ Title="Netflix", Url="http://www.netflix.com" }
     };
  }

  private void treeViewItem_DragOver(object sender, DragEventArgs e)
  {

  }

  private void treeViewItem_Drop(object sender, DragEventArgs e)
  {

  }

  private void treeViewItem_MouseMove(object sender, MouseEventArgs e)
  {

  }