Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF FileDrop Event: just allow a specific file extension

Tags:

c#

events

wpf

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?

like image 446
maveonair Avatar asked Apr 07 '09 09:04

maveonair


1 Answers

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:

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[];
}
like image 79
Christian Hubmann Avatar answered Sep 19 '22 06:09

Christian Hubmann