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

WPF 企業級框架實戰(6):整合 Prism 實現 MVVM 解耦與命令綁定

     編輯:關於.NET

前言

在前五篇奠定基礎架構(Ribbon、AvalonDock、主題切換)後,本文引入 Microsoft Prism Library,徹底落地 MVVM 模式:將視圖邏輯從 Code-behind 移至 ViewModel,實現「視圖與邏輯零耦合」,支援單元測試、設計時體驗與團隊並行開發。

為什麼需要 MVVM?

傳統 Code-behind 痛點:

  • XAML 事件名稱與後端方法強綁定,改名即報錯。
  • 視圖刪除導致邏輯碼同步消失,無法複用。
  • 單元測試幾乎不可能(需啟動 UI 執行緒)。
  • 設計師無法在 Blend 中獨立編輯介面。

MVVM 三大核心優勢:

  1. 低耦合:ViewModel 不引用 View,一個 VM 可綁定多個 View。
  2. 可測試性:純 C# 類別,可直接用 NUnit/xUnit 測試命令邏輯。
  3. 設計時支援:Blend 可直接對 VM 屬性進行資料綁定預覽。

步驟一:安裝 Prism 與建立目錄結構

  1. NuGet 安裝:Install-Package Prism.Wpf(或從 CodePlex 下載 Microsoft.Practices.Prism.dll)。
  2. 專案新增資料夾:Models、ViewModels。
  3. 對應 MainWindow.xaml 建立 MainWindowViewModel.cs。

解決方案目錄結構

步驟二:建立基礎 ViewModel

using Microsoft.Practices.Prism.ViewModel;
using Microsoft.Practices.Prism.Commands;
using System.Windows;

namespace TLAgent.SecurityManager.WPF.ViewModels
{
    public class MainWindowViewModel : NotificationObject
    {
        // 1. 宣告委托命令
        public DelegateCommand ExitSystemCommand { get; private set; }

        public MainWindowViewModel()
        {
            // 2. 實例化命令並綁定執行方法
            ExitSystemCommand = new DelegateCommand(this.OnExit);
        }

        private void OnExit()
        {
            var result = MessageBox.Show("確定要退出系統嗎?", "確認訊息",
                                         MessageBoxButton.OKCancel, MessageBoxImage.Question);
            if (result == MessageBoxResult.OK)
                Application.Current.Shutdown();
        }
    }
}

關鍵點**:

  • 繼承 NotificationObject(實作 INotifyPropertyChanged),支援屬性變更通知。
  • 使用 DelegateCommand 封裝 ICommand,支援 CanExecute 自動評估。

步驟三:XAML 綁定命令

<Fluent:Ribbon.Menu>
    <Fluent:Backstage Background="RoyalBlue">
        <Fluent:BackstageTabControl>
            <!-- Command 綁定 ViewModel 中的 DelegateCommand -->
            <Fluent:Button Header="退出系統"
                           Command="{Binding ExitSystemCommand}"
                           Icon="Images\close.png" />
        </Fluent:BackstageTabControl>
    </Fluent:Backstage>
</Fluent:Ribbon.Menu>

步驟四:設定 DataContext(兩種方式擇一)

方式 A:Code-behind 指定(推薦,便於 DI 容器注入)

using System.Windows;
using Fluent;
using TLAgent.SecurityManager.WPF.ViewModels;

namespace TLAgent.SecurityManager.WPF
{
    public partial class MainWindow : RibbonWindow
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainWindowViewModel(); // 關鍵一行
        }
    }
}

方式 B:XAML 宣告式指定

<Fluent:RibbonWindow ...
        xmlns:vm="clr-namespace:TLAgent.SecurityManager.WPF.ViewModels">
    <Fluent:RibbonWindow.DataContext>
        <vm:MainWindowViewModel />
    </Fluent:RibbonWindow.DataContext>
    ...
</Fluent:RibbonWindow>

XAML 設定 DataContext

執行驗證

點擊「退出系統」按鈕,彈出確認對話框,確認後應用程式正常關閉。View 完全不知情退出邏輯,僅透過 Command 綁定觸發 VM 方法。

執行效果圖

後續擴展方向

  • 引入 Unity/MEF 依賴注入容器,實現 ViewModel 自動建構與單例管理。
  • 實作 INavigationAware 支援區域導航與視圖切換。
  • 整合 EventAggregator 實現鬆散耦合的模組間通訊。
  • 加入 驗證框架(DataAnnotations / FluentValidation)於 VM 屬性。

範例原始碼**:TLAgent.SecurityManager.WPF.MVVM.Demo.rar

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved