2016-08-06 56 views
0

我從這裏複製該代碼: 我對文件有問題的dragoverWPF FileDragOver事件:只允許特定的文件擴展名錯誤

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[]; 
} 

但是我t在這裏使用多個擴展名: 如何可以?

喜歡的東西:

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

回答

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#問題。

+0

非常感謝兄弟 –

相關問題