【问题标题】:WPF FileDragOver Event: just allow a specific file extension ErrorWPF FileDragOver 事件:只允许特定的文件扩展名错误
【发布时间】:2016-08-07 14:08:15
【问题描述】:

我从这里复制了这段代码: 我在文件拖动时遇到问题

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")

【问题讨论】:

    标签: c#


    【解决方案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# 问题。

    【讨论】:

    • 非常感谢兄弟
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多