WPF FileDrop事件:只允许特定的文件扩展名

时间:2022-04-15 00:24:18

I have a WPF Control and I want to drop a specific file from my desktop to this control. This is not a heavy part but I would like to check the file extension to allow or disallow the dropping. What is the best way to solve this problem?

我有一个WPF控件,我想从我的桌面删除一个特定的文件到这个控件。这不是一个沉重的部分,但我想检查文件扩展名以允许或禁止删除。解决这个问题的最佳方法是什么?

1 个解决方案

#1


25  

I think this should work:

我认为这应该有效:

<Grid>
    <ListBox AllowDrop="True" DragOver="lbx1_DragOver" 
                                                      Drop="lbx1_Drop"></ListBox>
</Grid>

Let's assume you want to allow only C# files:

假设您只想允许C#文件:

private void lbx1_DragOver(object sender, DragEventArgs e)
{
   bool dropEnabled = true;
   if (e.Data.GetDataPresent(DataFormats.FileDrop, true))
   {
      string[] filenames = 
                       e.Data.GetData(DataFormats.FileDrop, true) as string[];

      foreach (string filename in filenames)
      {
         if(System.IO.Path.GetExtension(filename).ToUpperInvariant() != ".CS")
         {
            dropEnabled = false;
    break;
         }
       }
   }
   else
   {
      dropEnabled = false;
   }

   if (!dropEnabled)
   {
      e.Effects = DragDropEffects.None;
  e.Handled = true;
   }            
}


private void lbx1_Drop(object sender, DragEventArgs e)
{
    string[] droppedFilenames = 
                        e.Data.GetData(DataFormats.FileDrop, true) as string[];
}

#1


25  

I think this should work:

我认为这应该有效:

<Grid>
    <ListBox AllowDrop="True" DragOver="lbx1_DragOver" 
                                                      Drop="lbx1_Drop"></ListBox>
</Grid>

Let's assume you want to allow only C# files:

假设您只想允许C#文件:

private void lbx1_DragOver(object sender, DragEventArgs e)
{
   bool dropEnabled = true;
   if (e.Data.GetDataPresent(DataFormats.FileDrop, true))
   {
      string[] filenames = 
                       e.Data.GetData(DataFormats.FileDrop, true) as string[];

      foreach (string filename in filenames)
      {
         if(System.IO.Path.GetExtension(filename).ToUpperInvariant() != ".CS")
         {
            dropEnabled = false;
    break;
         }
       }
   }
   else
   {
      dropEnabled = false;
   }

   if (!dropEnabled)
   {
      e.Effects = DragDropEffects.None;
  e.Handled = true;
   }            
}


private void lbx1_Drop(object sender, DragEventArgs e)
{
    string[] droppedFilenames = 
                        e.Data.GetData(DataFormats.FileDrop, true) as string[];
}