標簽打印程序:配置窗體設置參數 (打印機、紙張、字體等),主窗體打印時需讀取這些配置。求共享方式。
| 模式 | 核心機制 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|---|
| 1. 單例配置類 (推薦) | 靜態實例持有配置對象,雙向綁定 UI | 內存高效、類型安全、支持屬性變更通知 (INotifyPropertyChanged)、易單元測試 | 需手寫單例模式 | 中小型應用、配置項較多、需實時同步 UI |
| 2. Application Settings (Settings.settings) | VS 內置機制,自動生成強類型類,持久化到 user.config | 零代碼持久化、支持用戶/應用範圍、自動綁定 PropertyGrid | 結構固定、難以共享複雜對象圖、多實例衝突 | 簡單標量配置、需自動保存上次設置 |
| 3. 依賴注入 (DI 容器) | 配置服務註冊為 Singleton,構造函數注入各窗體 | 解耦、可測試、生命周期可控、支援多實例/作用域 | 引入容器 (Autofac/MS DI)、樣板代碼多 | 中大型應用、模塊化架構、單元測試要求高 |
// Config.cs
public sealed class PrintConfig : INotifyPropertyChanged {
private static readonly Lazy _instance = new Lazy(() => new PrintConfig());
public static PrintConfig Instance => _instance.Value;
private PrintConfig() { LoadDefaults(); }
private string _printerName = "Default";
public string PrinterName {
get => _printerName;
set { if (_printerName != value) { _printerName = value; OnPropertyChanged(); } }
}
// ... 其他屬性: PaperSize, FontName, FontSize, Margin...
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string n = null)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(n));
public void LoadDefaults() { /* 從文件/注冊表/數據庫加載 */ }
public void Save() { /* 持久化 */ }
}
// ConfigForm.cs (配置窗體)
public partial class ConfigForm : Form {
public ConfigForm() {
InitializeComponent();
// 雙向綁定
txtPrinter.DataBindings.Add("Text", PrintConfig.Instance, "PrinterName", false, DataSourceUpdateMode.OnPropertyChanged);
// ... 其他控件綁定
}
private void btnSave_Click(object sender, EventArgs e) {
PrintConfig.Instance.Save();
this.Close();
}
}
// MainForm.cs (主窗體)
public partial class MainForm : Form {
private void btnPrint_Click(object sender, EventArgs e) {
var cfg = PrintConfig.Instance; // 直接獲取最新配置
using (var pd = new PrintDocument()) {
pd.PrinterSettings.PrinterName = cfg.PrinterName;
// ... 設置紙張、字體、邊距
pd.Print();
}
}
}
Properties > Settings;PrinterName (string, User)、PaperWidth (int, User)...;Properties.Settings.Default.PrinterName;txtPrinter.DataBindings.Add("Text", Properties.Settings.Default, "PrinterName");;Properties.Settings.Default.Save(); (自動寫入 user.config)。appsettings.json / Settings.settings (Application);Settings.settings (User) / 單例類 + JSON 文件;ProtectedData、KeyVault),不可明文;FileSystemWatcher 監聽配置文件變更,觸發重載。單例配置類 + 屬性綁定 + INotifyPropertyChanged 是 WinForms 共享配置的**工程化標準解法**:類型安全、實時同步、易測試、可擴展持久化。簡單項目可用內置 Settings.settings。大型項目引入 DI 容器管理配置服務生命周期。核心原則:**配置數據單一權威源,UI 僅為視圖投影**。