Skip to main content
 首页 » 编程设计

c#之WPF之DragOver 事件没有在我的列表框上触发

2024年02月05日7yxwkf

我正在尝试在我的 WPF 应用程序中实现拖放功能。我有一个列表框,我希望它能够从 Windows 资源管理器中拖放文件。然后将这些文件添加到列表框中。我曾经按照本教程进行过此工作:Drag and drop files to WPF application and asynchronously upload to ASP.NET Web API .减去上传到 web api 部分。我只想显示列表框中的文件。

问题是 DragOver 事件永远不会触发。我错过了什么?我早些时候已经开始工作了,但是一些小的调整把它搞砸了。

这是我的 XAML(简化了父元素):

<Window> 
  <Grid> 
    <TabControl> 
      <TabItem> 
        <Grid> 
          <GroupBox> 
            <ListBox Name="lstTarget" AllowDrop="True" 
                     Drop="lstTarget_Drop" 
                     DragOver="lstTarget_DragOver" 
                     DragLeave="lstTarget_DragLeave" 
                     BorderThickness="3" 
                     BorderBrush="Red" 
                     > 
            </ListBox> 

下面是我的代码

private void lstTarget_Drop(object sender, DragEventArgs e) 
{ 
    if (e.Data.GetDataPresent(DataFormats.FileDrop)) 
    { 
        string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); 
        foreach (string filePath in files) 
        { 
            lstTarget.Items.Add(filePath); 
        } 
    } 
 
    var listbox = sender as ListBox; 
    listbox.Background = new SolidColorBrush(Color.FromRgb(226, 226, 226)); 
} 
private void lstTarget_DragOver(object sender, DragEventArgs e) 
{ 
    lstTarget.BorderBrush = Brushes.Green; 
 
    if (e.Data.GetDataPresent(DataFormats.FileDrop)) 
    { 
        e.Effects = DragDropEffects.Copy; 
        var listbox = sender as ListBox; 
        listbox.Background = new SolidColorBrush(Color.FromRgb(155, 155, 155)            
    } 
    else 
    { 
        e.Effects = DragDropEffects.None; 
    } 
} 
 
private void lstTarget_DragLeave(object sender, DragEventArgs e) 
{ 
    var listbox = sender as ListBox; 
    listbox.Background = new SolidColorBrush(Color.FromRgb(226, 226, 226)); 
} 

请您参考如下方法:

好吧,我是个傻瓜。如果我以管理员身份运行我的应用程序,则无法从资源管理器中拖入项目。它们很可能在不同的安全上下文中运行。

我的代码没有任何问题。