首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> .NET 實例教學

WinForms 與 WPF 對話框完整比較:MessageBox、OpenFileDialog、SaveFileDialog

     編輯:.NET 實例教學

命名空間差異總覽

功能WinForms (System.Windows.Forms)WPF (System.Windows / Microsoft.Win32)
MessageBoxSystem.Windows.Forms.MessageBoxSystem.Windows.MessageBox
OpenFileDialogSystem.Windows.Forms.OpenFileDialogMicrosoft.Win32.OpenFileDialog
SaveFileDialogSystem.Windows.Forms.SaveFileDialogMicrosoft.Win32.SaveFileDialog

MessageBox 使用範例

WinForms

private void WFMessageBoxClicked(object sender, EventArgs e)
{
    System.Windows.Forms.MessageBox.Show(
        "Hello from Windows Forms!", 
        "Hello World!", 
        MessageBoxButtons.OK, 
        MessageBoxIcon.Information);
}

WPF

private void WPFMessageBoxClicked(object sender, RoutedEventArgs e)
{
    System.Windows.MessageBox.Show(
        "Hello from WPF!", 
        "Hello World!", 
        MessageBoxButton.OK, 
        MessageBoxImage.Information);
}

關鍵差異: WPF 版本使用 RoutedEventArgs、MessageBoxButton、MessageBoxImage 列舉,支援更豐富的 UI 整合。

檔案對話框使用範例

WinForms - OpenFileDialog

private void WinFormsDialogClicked(object sender, EventArgs e)
{
    using (var dialog = new System.Windows.Forms.OpenFileDialog())
    {
        dialog.Title = "選擇檔案";
        dialog.Filter = "文字檔 (*.txt)|*.txt|所有檔案 (*.*)|*.*";
        dialog.Multiselect = true;
        
        if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            foreach (var file in dialog.FileNames)
            {
                // 處理選取的檔案
            }
        }
    }
}

WPF - OpenFileDialog

private void WPFDialogClicked(object sender, RoutedEventArgs e)
{
    var dialog = new Microsoft.Win32.OpenFileDialog
    {
        Title = "選擇檔案",
        Filter = "文字檔 (*.txt)|*.txt|所有檔案 (*.*)|*.*",
        Multiselect = true
    };

    if (dialog.ShowDialog() == true)
    {
        foreach (var file in dialog.FileNames)
        {
            // 處理選取的檔案
        }
    }
}

SaveFileDialog 同理

兩者用法幾乎相同,僅差異在命名空間與回傳值判斷(WinForms 用 DialogResult.OK,WPF 用 true)。

深度差異分析

面向WinFormsWPF
對話框外觀傳統 Windows 樣式,隨作業系統版本支援自訂樣式、模板化、DPI 感知
檔案對話框舊版 Common Item Dialog (XP 風格)Vista+ IFileDialog 介面,支援 Library、搜尋箱
非同步支援無內建非同步可搭配 Task/await 模式包裝
跨執行緒呼叫需在 UI 執行緒需在 UI 執行緒 (Dispatcher)

最佳實務建議

  1. 專案一致性: 專案內統一使用對應框架的對話框,避免混用造成維護困擾。
  2. 資源釋放: WinForms 對話框實作 IDisposable,建議使用 using 區塊;WPF 版本雖非強制,但良好習慣同樣適用。
  3. 自訂對話框: 複雜情境建議自訂 Window/Page,而非強行修飾系統對話框。
  4. 單元測試: 將對話框呼叫封裝成介面 (IDialogService),方便 Mock 測試。

常見陷阱

  • WPF 專案誤引用 System.Windows.Forms 導致組件衝突、部署體積膨脹。
  • WinForms 專案引用 PresentationFramework 只為用 WPF MessageBox,得不償失。
  • 檔案對話框 InitialDirectory 未設定,導致預設開啟「文件庫」或系統目錄,體驗不佳。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved