WPF FileDragOver事件:只允许特定的文件扩展名错误

时间:2016-08-06 19:58:11

标签: c#

我从这里复制了这段代码: 我在文件dragover上有问题

Copy From Here

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

我们假设您只想要允许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[];
}

但我想在这里使用多个扩展名: 怎么可以?

喜欢的东西:

 if(System.IO.Path.GetExtension(filename).ToUpperInvariant() != ".mp3,.mp4,.mkv")

1 个答案:

答案 0 :(得分:1)

var allowedExtensions = new [] { ".MP3", ".MP4", ".MKV" };

//  If All of the filename extensions are contained in allowedExtensions, 
//  set dropEnabled to true. 

dropEnabled = filenames.All(fn =>
        allowedExtensions.Contains(System.IO.Path.GetExtension(fn).ToUpperInvariant())
    );

这是一个占用更多空间的版本,但它更容易理解:

var allowedExtensions = new [] { ".MP3", ".MP4", ".MKV" };

foreach (var fn in filenames)
{
    var ext = System.IO.Path.GetExtension(fn).ToUpperInvariant();

    if (!allowedExtensions.Contains(ext))
    {
        dropEnabled = false;
        break;
    }
}

这个问题与WPF无关;这是一个C#问题。