WPF FileDrop事件:只允许特定的文件扩展名 [英] WPF FileDrop Event: just allow a specific file extension

查看:178
本文介绍了WPF FileDrop事件:只允许特定的文件扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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?

推荐答案

我觉得这应该工作:

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

让我们假设你想只允许C#文件:

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

这篇关于WPF FileDrop事件:只允许特定的文件扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆