- 首發公眾號:Dotnet9
- 作者:沙漠之盡頭的狼
- 日期:202-11-27
一、本文開始之前
上傳檔案時,一般是提供一個上傳按鈕,點擊上傳,彈出檔案(或者目錄選擇對話框),選擇檔案(或者目錄)后,從對話框物件中取得檔案路徑后,再進行上傳操作,

選擇對話框代碼如下:
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Title = "選擇Exe檔案";
openFileDialog.Filter = "exe檔案|*.exe";
openFileDialog.FileName = string.Empty;
openFileDialog.FilterIndex = 1;
openFileDialog.Multiselect = false;
openFileDialog.RestoreDirectory = true;
openFileDialog.DefaultExt = "exe";
if (openFileDialog.ShowDialog() == false)
{
return;
}
string txtFile = openFileDialog.FileName;
但一般來說,對用戶體驗最好的,應該是直接滑鼠拖拽檔案了:

下面簡單說說WPF中檔案拖拽的實作方式,
二、WPF中怎樣拖拽檔案呢?
其實很簡單,只要拖拽接受控制元件(或容器)注冊這兩個事件即可:DragEnter、Drop,
先看看我的實作效果:

Xaml中注冊事件
注冊事件:
<Grid MouseMove="Grid_MouseMove" AllowDrop="True" Drop="Grid_Drop" DragEnter="Grid_DragEnter">
事件處理方法:
- Grid_DragEnter處理方法
private void Grid_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effects = DragDropEffects.Link;
}
else
{
e.Effects = DragDropEffects.None;
}
}
DragDropEffects.Link:處理拖拽檔案操作
- Grid_Drop處理方法
這是處理實際拖拽操作的方法,得到拖拽的檔案路徑(如果是作業系統檔案快捷方式(擴展名為lnk),則需要使用com組件(不是本文講解重點,具體看本文開源專案)取得實際檔案路徑)后,即可處理后續操作(比如檔案上傳),
private void Grid_Drop(object sender, DragEventArgs e)
{
try
{
var fileName = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
MenuItemInfo menuItem = new MenuItemInfo() { FilePath = fileName };
// 快捷方式需要獲取目標檔案路徑
if (fileName.ToLower().EndsWith("lnk"))
{
WshShell shell = new WshShell();
IWshShortcut wshShortcut = (IWshShortcut)shell.CreateShortcut(fileName);
menuItem.FilePath = wshShortcut.TargetPath;
}
ImageSource imageSource = SystemIcon.GetImageSource(true, menuItem.FilePath);
System.IO.FileInfo file = new System.IO.FileInfo(fileName);
if (string.IsNullOrWhiteSpace(file.Extension))
{
menuItem.Name = file.Name;
}
else
{
menuItem.Name = file.Name.Substring(0, file.Name.Length - file.Extension.Length);
}
menuItem.Type = MenuItemType.Exe;
if (ConfigHelper.AddNewMenuItem(menuItem))
{
AddNewMenuItem(menuItem);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
三、本文Over
功能很簡單,不求精深,會用就行,
時間如流水,只能流去不流回,
- 首發公眾號:Dotnet9
- 作者:沙漠之盡頭的狼
- 日期:202-11-27
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/228268.html
標籤:WPF
上一篇:WPF實作等待界面效果
下一篇:WPF之認識XAML

