winforms

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Windows Forms

Windows Forms

Trigger On

触发场景

  • working on Windows Forms UI, event-driven workflows, or classic LOB applications
  • migrating WinForms from .NET Framework to modern .NET
  • cleaning up oversized form code or designer coupling
  • implementing data binding, validation, or control customization
  • 开发Windows Forms UI、事件驱动工作流或经典LOB应用程序
  • 将WinForms从.NET Framework迁移至现代.NET
  • 清理臃肿的窗体代码或设计器耦合问题
  • 实现数据绑定、验证或控件自定义

Workflow

工作流程

  1. Respect designer boundaries — never edit
    .Designer.cs
    directly; changes are lost on regeneration.
  2. Separate business logic from forms — use MVP (Model-View-Presenter) pattern. Forms orchestrate UI; presenters contain logic; services handle data access.
    csharp
    // View interface — forms implement this
    public interface ICustomerView
    {
        string CustomerName { get; set; }
        event EventHandler SaveRequested;
        void ShowError(string message);
    }
    
    // Presenter — testable without UI
    public class CustomerPresenter
    {
        private readonly ICustomerView _view;
        private readonly ICustomerService _service;
        public CustomerPresenter(ICustomerView view, ICustomerService service)
        {
            _view = view;
            _service = service;
            _view.SaveRequested += async (s, e) =>
            {
                try { await _service.SaveAsync(_view.CustomerName); }
                catch (Exception ex) { _view.ShowError(ex.Message); }
            };
        }
    }
  3. Use DI from Program.cs (.NET 6+):
    csharp
    var services = new ServiceCollection();
    services.AddSingleton<ICustomerService, CustomerService>();
    services.AddTransient<MainForm>();
    using var sp = services.BuildServiceProvider();
    Application.Run(sp.GetRequiredService<MainForm>());
  4. Use data binding via
    BindingSource
    and
    INotifyPropertyChanged
    instead of manual control population. See references/patterns.md for complete binding patterns.
  5. Use async/await for I/O operations — disable controls during loading, use
    Progress<T>
    for progress reporting. Never block the UI thread.
  6. Validate with
    ErrorProvider
    and the
    Validating
    event. Call
    ValidateChildren()
    before save operations.
  7. Modernize incrementally — prefer better structure over big-bang rewrites. Use .NET 8+ features (button commands, stock icons) when available.
  1. 尊重设计器边界 — 切勿直接编辑
    .Designer.cs
    文件;重新生成时手动修改的内容会丢失。
  2. 将业务逻辑与窗体分离 — 使用MVP(Model-View-Presenter)模式。窗体负责协调UI;呈现器包含逻辑;服务层处理数据访问。
    csharp
    // View interface — forms implement this
    public interface ICustomerView
    {
        string CustomerName { get; set; }
        event EventHandler SaveRequested;
        void ShowError(string message);
    }
    
    // Presenter — testable without UI
    public class CustomerPresenter
    {
        private readonly ICustomerView _view;
        private readonly ICustomerService _service;
        public CustomerPresenter(ICustomerView view, ICustomerService service)
        {
            _view = view;
            _service = service;
            _view.SaveRequested += async (s, e) =>
            {
                try { await _service.SaveAsync(_view.CustomerName); }
                catch (Exception ex) { _view.ShowError(ex.Message); }
            };
        }
    }
  3. 从Program.cs使用依赖注入(DI)(.NET 6+):
    csharp
    var services = new ServiceCollection();
    services.AddSingleton<ICustomerService, CustomerService>();
    services.AddTransient<MainForm>();
    using var sp = services.BuildServiceProvider();
    Application.Run(sp.GetRequiredService<MainForm>());
  4. 通过
    BindingSource
    INotifyPropertyChanged
    实现数据绑定
    ,而非手动填充控件。完整的绑定模式请参阅references/patterns.md
  5. 对I/O操作使用async/await — 加载期间禁用控件,使用
    Progress<T>
    报告进度。切勿阻塞UI线程。
  6. 使用
    ErrorProvider
    Validating
    事件进行验证
    。保存操作前调用
    ValidateChildren()
  7. 逐步现代化 — 优先优化结构而非大规模重写。若可用,使用.NET 8+特性(按钮命令、标准图标)。

Current Upstream Notes

当前上游说明

  • The August 2026 Windows Forms overview remains focused on Windows desktop, designer-driven controls, events, data binding, and migration to modern .NET. It does not change the framework-selection guidance: improve form boundaries and designer safety before proposing a rewrite.
  • For docs-driven updates, validate whether the app targets .NET Framework, modern .NET, or mixed libraries before changing project format, designer files, or deployment assumptions.
mermaid
flowchart LR
  A["Form event"] --> B["Presenter handles logic"]
  B --> C["Service layer / data access"]
  C --> D["Update view via interface"]
  D --> E["Validate and display results"]
  • 2026年8月的Windows Forms概述仍聚焦于Windows桌面、设计器驱动控件、事件、数据绑定以及迁移至现代.NET。它并未改变框架选择指导建议:在提议重写之前,先优化窗体边界和设计器安全性。
  • 对于基于文档的更新,在更改项目格式、设计器文件或部署假设之前,需验证应用程序是面向.NET Framework、现代.NET还是混合库。
mermaid
flowchart LR
  A["Form event"] --> B["Presenter handles logic"]
  B --> C["Service layer / data access"]
  C --> D["Update view via interface"]
  D --> E["Validate and display results"]

Key Decisions

关键决策

DecisionGuidance
MVP vs MVVMPrefer MVP for WinForms — simpler with event-driven model
BindingSource vs manualAlways prefer BindingSource for list/detail binding
Sync vs async I/OAlways async — use
async void
only for event handlers
Custom controlsExtract reusable
UserControl
when form grows beyond ~300 lines
.NET Framework → .NETUse the official migration guide; validate designer compatibility first
决策指导建议
MVP vs MVVMWinForms优先使用MVP — 与事件驱动模型更契合
BindingSource vs 手动实现列表/详情绑定始终优先使用BindingSource
同步vs异步I/O始终使用异步 — 仅在事件处理程序中使用
async void
自定义控件当窗体代码超过约300行时,提取可复用的
UserControl
.NET Framework → .NET使用官方迁移指南;首先验证设计器兼容性

Deliver

交付成果

  • less brittle form code with clear UI/logic separation
  • MVP pattern with testable presenters
  • pragmatic modernization guidance for WinForms-heavy apps
  • data binding and validation patterns that reduce manual wiring
  • 具有清晰UI/逻辑分离的低脆弱性窗体代码
  • 具备可测试呈现器的MVP模式
  • 针对WinForms重度应用的务实现代化指导
  • 减少手动编写的数据绑定和验证模式

Validate

验证标准

  • designer files stay stable and are not hand-edited
  • forms are not acting as the application service layer
  • async operations do not block the UI thread
  • validation is implemented consistently with ErrorProvider
  • Windows-only runtime behavior is tested on target
  • 设计器文件保持稳定,未被手动编辑
  • 窗体未充当应用程序服务层
  • 异步操作未阻塞UI线程
  • 使用ErrorProvider一致实现验证
  • 在目标环境测试仅Windows运行时行为

References

参考资料

  • references/patterns.md - WinForms architectural patterns (MVP, MVVM, Passive View), data binding, validation, form communication, threading, DI setup, and .NET 8+ features
  • references/migration.md - step-by-step migration from .NET Framework to modern .NET, common issues, deployment options, and gradual migration strategies
  • references/patterns.md - WinForms架构模式(MVP、MVVM、被动视图)、数据绑定、验证、窗体通信、线程、DI设置以及.NET 8+特性
  • references/migration.md - 从.NET Framework逐步迁移至现代.NET的步骤、常见问题、部署选项以及渐进式迁移策略