tags:

views:

326

answers:

1

Hi there,

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?

Thanks!

+1  A: 

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