Skip to content

使用 AI 进行组件生成

1. 定义项目结构

Step 1. Project Setup

Framework: .NET 10

Solution Name: SmartTextBoxApp

Output Format: ZIP file

Solution Structure:
- DemoApp (WPF App)
- JamesSmartTextBox (Class Library)

DemoApp:
- SmartTextBox examples in MainWindow.xaml
JamesSmartTextBox:
- SmartTextBox.cs (CustomControl, inherits TextBox)
- SmartTextBox.xaml (ResourceDictionary)

Project Structure:
1. UI/Units/SmartTextBox.cs
2. Themes/Units/SmartTextBox.xaml
3. Themes/Generic.xaml (Merge SmartTextBox.xaml)

Important:
- Include AssemblyInfo.cs
- Generic.xaml merges SmartTextBox.xaml
- SmartTextBox.cs sets DefaultStyleKey
  • 输出格式是 zip 是因为使用的是网页对话的 AI;
  • 对于 WPF 组件来说,应用组件库的应用会默认导入 Themes/Generic.xaml 资源字典;同时需要添加 WPF 组件库的声明在 AssemblyInfo.cs 中;

2. 定义组件功能

Step 2. Add Validation

SmartTextBox DependencyProperty (6):
- Header (string)
- PlaceHolder (string)
- CornerRadius (CornerRadius)
- Validator (IValidator)
- IsValid (bool)
- ErrorMessage (string)

IValidator:
- Message (string)
- Validate(string value) → bool

Behavior:
- Auto-validate on Text change, show red border and ErrorMessage on invalid

Validator setup:
- IValidator + 2 Validators in same file
- Path: JamesSmartTextBox/Local/Validators/IValidator.cs

DemoApp:
- Apply Validators in MainWindow.xaml

Important:
- Only 6 DPs
- No comments/regions
  • 进一步定义了数据结构、需要实现的功能、功能发生的时机、功能的结果;
  • 如有新文件,指明路径;
  • 并不需要具体说明实现细节;

在这个例子中,新的 TextBox 的主要目的是实现文字输入时(事件时机)的数据验证功能,这是一个简洁直接且独立的目的(需求)。

或者从另外一个角度,每个依赖属性的声明都是它需要的功能点,告诉 AI 定义这些依赖属性,它自己能够理解是要做什么。

3. 基于已有组件添加额外功能

Step 3. Built-in Validators

Add Validators inheriting IValidator:
- Email
- Password (min 8 chars, uppercase + lowercase + numbers)
- URL
- Passport
- CreditCard

DemoApp:
- Demonstrate all Validators in MainWindow.xaml

总结

在这个例子中,三个步骤都在同一个对话中使用,且每个步骤的标题(Step)也是提示词的一部分。

| 使用 VS 的 Github Copilot、相同的 AI 模型、大致相同的提示词(项目结构、主题等有修改),产生的项目结果见 ref 3。

ref

  1. Github: JamesnetGroup/smarttextbox
  2. Bilibili: JamesnetGroup
  3. Github: orrest/Tests.SmartTextBoxDemo