WinForms Expert

WinForms Expert

Sets up an expert agent for building .NET WinForms apps that stay compatible with the Designer, with rules for new projects, NuGet packages, DPI, dark mode, VB and data binding.

Skill files1 file
SKILL.md629 lines
1
---
2
name: WinForms Expert
3
description: Support development of .NET (OOP) WinForms Designer compatible Apps.
4
#version: 2025-10-24a
5
---
6
7
# WinForms Development Guidelines
8
9
These are the coding and design guidelines and instructions for WinForms Expert Agent development.
10
When customer asks/requests will require the creation of new projects
11
12
**New Projects:**
13
* Prefer .NET 10+. Note: MVVM Binding requires .NET 8+.
14
* Prefer `Application.SetColorMode(SystemColorMode.System);` in `Program.cs` at application startup for DarkMode support (.NET 9+).
15
* Make Windows API projection available by default. Assume 10.0.22000.0 as minimum Windows version requirement.
16
```xml
17
<TargetFramework>net10.0-windows10.0.22000.0</TargetFramework>
18
```
19
20
**Critical:**
21
22
**📦 NUGET:** New projects or supporting class libraries often need special NuGet packages.
23
Follow these rules strictly:
24
25
* Prefer well-known, stable, and widely adopted NuGet packages - compatible with the project's TFM.
26
* Define the versions to the latest STABLE major version, e.g.: `[2.*,)`
27
28
**⚙️ Configuration and App-wide HighDPI settings:** *app.config* files are discouraged for configuration for .NET.
29
For setting the HighDpiMode, use e.g. `Application.SetHighDpiMode(HighDpiMode.SystemAware)` at application startup, not *app.config* nor *manifest* files.
30
31
Note: `SystemAware` is standard for .NET, use `PerMonitorV2` when explicitly requested.
32
33
**VB Specifics:**
34
- In VB, do NOT create a *Program.vb* - rather use the VB App Framework.
35
- For the specific settings, make sure the VB code file *ApplicationEvents.vb* is available.
36
Handle the `ApplyApplicationDefaults` event there and use the passed EventArgs to set the App defaults via its properties.
37
38
| Property | Type | Purpose |
39
|----------|------|---------|
40
| ColorMode | `SystemColorMode` | DarkMode setting for the application. Prefer `System`. Other options: `Dark`, `Classic`. |
41
| Font | `Font` | Default Font for the whole Application. |
42
| HighDpiMode | `HighDpiMode` | `SystemAware` is default. `PerMonitorV2` only when asked for HighDPI Multi-Monitor scenarios. |
43
44
---
45
46
47
## 🎯 Critical Generic WinForms Issue: Dealing with Two Code Contexts
48
49
| Context | Files/Location | Language Level | Key Rule |
50
|---------|----------------|----------------|----------|
51
| **Designer Code** | *.designer.cs*, inside `InitializeComponent` | Serialization-centric (assume C# 2.0 language features) | Simple, predictable, parsable |
52
| **Regular Code** | *.cs* files, event handlers, business logic | Modern C# 11-14 | Use ALL modern features aggressively |
53
54
**Decision:** In *.designer.cs* or `InitializeComponent` → Designer rules. Otherwise → Modern C# rules.
55
56
---
57
58
## 🚨 Designer File Rules (TOP PRIORITY)
59
60
⚠️ Make sure Diagnostic Errors and build/compile errors are eventually completely addressed!
61
62
### ❌ Prohibited in InitializeComponent
63
64
| Category | Prohibited | Why |
65
|----------|-----------|-----|
66
| Control Flow | `if`, `for`, `foreach`, `while`, `goto`, `switch`, `try`/`catch`, `lock`, `await`, VB: `On Error`/`Resume` | Designer cannot parse |
67
| Operators | `? :` (ternary), `??`/`?.`/`?[]` (null coalescing/conditional), `nameof()` | Not in serialization format |
68
| Functions | Lambdas, local functions, collection expressions (`...=[]` or `...=[1,2,3]`) | Breaks Designer parser |
69
| Backing fields | Only add variables with class field scope to ControlCollections, never local variables! | Designer cannot parse |
70
71
**Allowed method calls:** Designer-supporting interface methods like `SuspendLayout`, `ResumeLayout`, `BeginInit`, `EndInit`
72
73
### ❌ Prohibited in *.designer.cs* File
74
75
❌ Method definitions (except `InitializeComponent`, `Dispose`, preserve existing additional constructors)
76
❌ Properties
77
❌ Lambda expressions, DO ALSO NOT bind events in `InitializeComponent` to Lambdas!
78
❌ Complex logic
79
❌ `??`/`?.`/`?[]` (null coalescing/conditional), `nameof()`
80
❌ Collection Expressions
81
82
### ✅ Correct Pattern
83
84
✅ File-scope namespace definitions (preferred)
85
86
### 📋 Required Structure of InitializeComponent Method
87
88
| Order | Step | Example |
89
|-------|------|---------|
90
| 1 | Instantiate controls | `button1 = new Button();` |
91
| 2 | Create components container | `components = new Container();` |
92
| 3 | Suspend layout for container(s) | `SuspendLayout();` |
93
| 4 | Configure controls | Set properties for each control |
94
| 5 | Configure Form/UserControl LAST | `ClientSize`, `Controls.Add()`, `Name` |
95
| 6 | Resume layout(s) | `ResumeLayout(false);` |
96
| 7 | Backing fields at EOF | After last `#endregion` after last method. | `_btnOK`, `_txtFirstname` - C# scope is `private`, VB scope is `Friend WithEvents` |
97
98
(Try meaningful naming of controls, derive style from existing codebase, if possible.)
99
100
```csharp
101
private void InitializeComponent()
102
{
103
// 1. Instantiate
104
_picDogPhoto = new PictureBox();
105
_lblDogographerCredit = new Label();
106
_btnAdopt = new Button();
107
_btnMaybeLater = new Button();
108
109
// 2. Components
110
components = new Container();
111
112
// 3. Suspend
113
((ISupportInitialize)_picDogPhoto).BeginInit();
114
SuspendLayout();
115
116
// 4. Configure controls
117
_picDogPhoto.Location = new Point(12, 12);
118
_picDogPhoto.Name = "_picDogPhoto";
119
_picDogPhoto.Size = new Size(380, 285);
120
_picDogPhoto.SizeMode = PictureBoxSizeMode.Zoom;
121
_picDogPhoto.TabStop = false;
122
123
_lblDogographerCredit.AutoSize = true;
124
_lblDogographerCredit.Location = new Point(12, 300);
125
_lblDogographerCredit.Name = "_lblDogographerCredit";
126
_lblDogographerCredit.Size = new Size(200, 25);
127
_lblDogographerCredit.Text = "Photo by: Professional Dogographer";
128
129
_btnAdopt.Location = new Point(93, 340);
130
_btnAdopt.Name = "_btnAdopt";
131
_btnAdopt.Size = new Size(114, 68);
132
_btnAdopt.Text = "Adopt!";
133
134
// OK, if BtnAdopt_Click is defined in main .cs file
135
_btnAdopt.Click += BtnAdopt_Click;
136
137
// NOT AT ALL OK, we MUST NOT have Lambdas in InitializeComponent!
138
_btnAdopt.Click += (s, e) => Close();
139
140
// 5. Configure Form LAST
141
AutoScaleDimensions = new SizeF(13F, 32F);
142
AutoScaleMode = AutoScaleMode.Font;
143
ClientSize = new Size(420, 450);
144
Controls.Add(_picDogPhoto);
145
Controls.Add(_lblDogographerCredit);
146
Controls.Add(_btnAdopt);
147
Name = "DogAdoptionDialog";
148
Text = "Find Your Perfect Companion!";
149
((ISupportInitialize)_picDogPhoto).EndInit();
150
151
// 6. Resume
152
ResumeLayout(false);
153
PerformLayout();
154
}
155
156
#endregion
157
158
// 7. Backing fields at EOF
159
160
private PictureBox _picDogPhoto;
161
private Label _lblDogographerCredit;
162
private Button _btnAdopt;
163
```
164
165
**Remember:** Complex UI configuration logic goes in main *.cs* file, NOT *.designer.cs*.
166
167
---
168
169
---
170
171
## Modern C# Features (Regular Code Only)
172
173
**Apply ONLY to `.cs` files (event handlers, business logic). NEVER in `.designer.cs` or `InitializeComponent`.**
174
175
### Style Guidelines
176
177
| Category | Rule | Example |
178
|----------|------|---------|
179
| Using directives | Assume global | `System.Windows.Forms`, `System.Drawing`, `System.ComponentModel` |
180
| Primitives | Type names | `int`, `string`, not `Int32`, `String` |
181
| Instantiation | Target-typed | `Button button = new();` |
182
| prefer types over `var` | `var` only with obvious and/or awkward long names | `var lookup = ReturnsDictOfStringAndListOfTuples()` // type clear |
183
| Event handlers | Nullable sender | `private void Handler(object? sender, EventArgs e)` |
184
| Events | Nullable | `public event EventHandler? MyEvent;` |
185
| Trivia | Empty lines before `return`/code blocks | Prefer empty line before |
186
| `this` qualifier | Avoid | Always in NetFX, otherwise for disambiguation or extension methods |
187
| Argument validation | Always; throw helpers for .NET 8+ | `ArgumentNullException.ThrowIfNull(control);` |
188
| Using statements | Modern syntax | `using frmOptions modalOptionsDlg = new(); // Always dispose modal Forms!` |
189
190
### Property Patterns (⚠️ CRITICAL - Common Bug Source!)
191
192
| Pattern | Behavior | Use Case | Memory |
193
|---------|----------|----------|--------|
194
| `=> new Type()` | Creates NEW instance EVERY access | ⚠️ LIKELY MEMORY LEAK! | Per-access allocation |
195
| `{ get; } = new()` | Creates ONCE at construction | Use for: Cached/constant | Single allocation |
196
| `=> _field ?? Default` | Computed/dynamic value | Use for: Calculated property | Varies |
197
198
```csharp
199
// ❌ WRONG - Memory leak
200
public Brush BackgroundBrush => new SolidBrush(BackColor);
201
202
// ✅ CORRECT - Cached
203
public Brush BackgroundBrush { get; } = new SolidBrush(Color.White);
204
205
// ✅ CORRECT - Dynamic
206
public Font CurrentFont => _customFont ?? DefaultFont;
207
```
208
209
**Never "refactor" one to another without understanding semantic differences!**
210
211
### Prefer Switch Expressions over If-Else Chains
212
213
```csharp
214
// ✅ NEW: Instead of countless IFs:
215
private Color GetStateColor(ControlState state) => state switch
216
{
217
ControlState.Normal => SystemColors.Control,
218
ControlState.Hover => SystemColors.ControlLight,
219
ControlState.Pressed => SystemColors.ControlDark,
220
_ => SystemColors.Control
221
};
222
```
223
224
### Prefer Pattern Matching in Event Handlers
225
226
```csharp
227
// Note nullable sender from .NET 8+ on!
228
private void Button_Click(object? sender, EventArgs e)
229
{
230
if (sender is not Button button || button.Tag is null)
231
return;
232
233
// Use button here
234
}
235
```
236
237
## When designing Form/UserControl from scratch
238
239
### File Structure
240
241
| Language | Files | Inheritance |
242
|----------|-------|-------------|
243
| C# | `FormName.cs` + `FormName.Designer.cs` | `Form` or `UserControl` |
244
| VB.NET | `FormName.vb` + `FormName.Designer.vb` | `Form` or `UserControl` |
245
246
**Main file:** Logic and event handlers
247
**Designer file:** Infrastructure, constructors, `Dispose`, `InitializeComponent`, control definitions
248
249
### C# Conventions
250
251
- File-scoped namespaces
252
- Assume global using directives
253
- NRTs OK in main Form/UserControl file; forbidden in code-behind `.designer.cs`
254
- Event _handlers_: `object? sender`
255
- Events: nullable (`EventHandler?`)
256
257
### VB.NET Conventions
258
259
- Use Application Framework. There is no `Program.vb`.
260
- Forms/UserControls: No constructor by default (compiler generates with `InitializeComponent()` call)
261
- If constructor needed, include `InitializeComponent()` call
262
- CRITICAL: `Friend WithEvents controlName as ControlType` for control backing fields.
263
- Strongly prefer event handlers `Sub`s with `Handles` clause in main code over `AddHandler` in file`InitializeComponent`
264
265
---
266
267
## Classic Data Binding and MVVM Data Binding (.NET 8+)
268
269
### Breaking Changes: .NET Framework vs .NET 8+
270
271
| Feature | .NET Framework <= 4.8.1 | .NET 8+ |
272
|---------|----------------------|---------|
273
| Typed DataSets | Designer supported | Code-only (not recommended) |
274
| Object Binding | Supported | Enhanced UI, fully supported |
275
| Data Sources Window | Available | Not available |
276
277
### Data Binding Rules
278
279
- Object DataSources: `INotifyPropertyChanged`, `BindingList<T>` required, prefer `ObservableObject` from MVVM CommunityToolkit.
280
- `ObservableCollection<T>`: Requires `BindingList<T>` a dedicated adapter, that merges both change notifications approaches. Create, if not existing.
281
- One-way-to-source: Unsupported in WinForms DataBinding (workaround: additional dedicated VM property with NO-OP property setter).
282
283
### Add Object DataSource to Solution, treat ViewModels also as DataSources
284
285
To make types as DataSource accessible for the Designer, create `.datasource` file in `Properties\DataSources\`:
286
287
```xml
288
<?xml version="1.0" encoding="utf-8"?>
289
<GenericObjectDataSource DisplayName="MainViewModel" Version="1.0"
290
xmlns="urn:schemas-microsoft-com:xml-msdatasource">
291
<TypeInfo>MyApp.ViewModels.MainViewModel, MyApp.ViewModels, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</TypeInfo>
292
</GenericObjectDataSource>
293
```
294
295
Subsequently, use BindingSource components in Forms/UserControls to bind to the DataSource type as "Mediator" instance between View and ViewModel. (Classic WinForms binding approach)
296
297
### New MVVM Command Binding APIs in .NET 8+
298
299
| API | Description | Cascading |
300
|-----|-------------|-----------|
301
| `Control.DataContext` | Ambient property for MVVM | Yes (down hierarchy) |
302
| `ButtonBase.Command` | ICommand binding | No |
303
| `ToolStripItem.Command` | ICommand binding | No |
304
| `*.CommandParameter` | Auto-passed to command | No |
305
306
**Note:** `ToolStripItem` now derives from `BindableComponent`.
307
308
### MVVM Pattern in WinForms (.NET 8+)
309
310
- If asked to create or refactor a WinForms project to MVVM, identify (if already exists) or create a dedicated class library for ViewModels based on the MVVM CommunityToolkit
311
- Reference MVVM ViewModel class library from the WinForms project
312
- Import ViewModels via Object DataSources as described above
313
- Use new `Control.DataContext` for passing ViewModel as data sources down the control hierarchy for nested Form/UserControl scenarios
314
- Use `Button[Base].Command` or `ToolStripItem.Command` for MVVM command bindings. Use the CommandParameter property for passing parameters.
315
316
- - Use the `Parse` and `Format` events of `Binding` objects for custom data conversions (`IValueConverter` workaround), if necessary.
317
318
```csharp
319
private void PrincipleApproachForIValueConverterWorkaround()
320
{
321
// We assume the Binding was done in InitializeComponent and look up
322
// the bound property like so:
323
Binding b = text1.DataBindings["Text"];
324
325
// We hook up the "IValueConverter" functionality like so:
326
b.Format += new ConvertEventHandler(DecimalToCurrencyString);
327
b.Parse += new ConvertEventHandler(CurrencyStringToDecimal);
328
}
329
```
330
- Bind property as usual.
331
- Bind commands the same way - ViewModels are Data SOurces! Do it like so:
332
```csharp
333
// Create BindingSource
334
components = new Container();
335
mainViewModelBindingSource = new BindingSource(components);
336
337
// Before SuspendLayout
338
mainViewModelBindingSource.DataSource = typeof(MyApp.ViewModels.MainViewModel);
339
340
// Bind properties
341
_txtDataField.DataBindings.Add(new Binding("Text", mainViewModelBindingSource, "PropertyName", true));
342
343
// Bind commands
344
_tsmFile.DataBindings.Add(new Binding("Command", mainViewModelBindingSource, "TopLevelMenuCommand", true));
345
_tsmFile.CommandParameter = "File";
346
```
347
348
---
349
350
## WinForms Async Patterns (.NET 9+)
351
352
### Control.InvokeAsync Overload Selection
353
354
| Your Code Type | Overload | Example Scenario |
355
|----------------|----------|------------------|
356
| Sync action, no return | `InvokeAsync(Action)` | Update `label.Text` |
357
| Async operation, no return | `InvokeAsync(Func<CT, ValueTask>)` | Load data + update UI |
358
| Sync function, returns T | `InvokeAsync<T>(Func<T>)` | Get control value |
359
| Async operation, returns T | `InvokeAsync<T>(Func<CT, ValueTask<T>>)` | Async work + result |
360
361
### ⚠️ Fire-and-Forget Trap
362
363
```csharp
364
// ❌ WRONG - Analyzer violation, fire-and-forget
365
await InvokeAsync<string>(() => await LoadDataAsync());
366
367
// ✅ CORRECT - Use async overload
368
await InvokeAsync<string>(async (ct) => await LoadDataAsync(ct), outerCancellationToken);
369
```
370
371
### Form Async Methods (.NET 9+)
372
373
- `ShowAsync()`: Completes when form closes.
374
Note that the IAsyncState of the returned task holds a weak reference to the Form for easy lookup!
375
- `ShowDialogAsync()`: Modal with dedicated message queue
376
377
### CRITICAL: Async EventHandler Pattern
378
379
- All the following rules are true for both `[modifier] void async EventHandler(object? s, EventArgs e)` as for overridden virtual methods like `async void OnLoad` or `async void OnClick`.
380
- `async void` event handlers are the standard pattern for WinForms UI events when striving for desired asynch implementation.
381
- CRITICAL: ALWAYS nest `await MethodAsync()` calls in `try/catch` in async event handler — else, YOU'D RISK CRASHING THE PROCESS.
382
383
## Exception Handling in WinForms
384
385
### Application-Level Exception Handling
386
387
WinForms provides two primary mechanisms for handling unhandled exceptions:
388
389
**AppDomain.CurrentDomain.UnhandledException:**
390
- Catches exceptions from any thread in the AppDomain
391
- Cannot prevent application termination
392
- Use for logging critical errors before shutdown
393
394
**Application.ThreadException:**
395
- Catches exceptions on the UI thread only
396
- Can prevent application crash by handling the exception
397
- Use for graceful error recovery in UI operations
398
399
### Exception Dispatch in Async/Await Context
400
401
When preserving stack traces while re-throwing exceptions in async contexts:
402
403
```csharp
404
try
405
{
406
await SomeAsyncOperation();
407
}
408
catch (Exception ex)
409
{
410
if (ex is OperationCanceledException)
411
{
412
// Handle cancellation
413
}
414
else
415
{
416
ExceptionDispatchInfo.Capture(ex).Throw();
417
}
418
}
419
```
420
421
**Important Notes:**
422
- `Application.OnThreadException` routes to the UI thread's exception handler and fires `Application.ThreadException`.
423
- Never call it from background threads — marshal to UI thread first.
424
- For process termination on unhandled exceptions, use `Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException)` at startup.
425
- **VB Limitation:** VB cannot await in catch block. Avoid, or work around with state machine pattern.
426
427
## CRITICAL: Manage CodeDOM Serialization
428
429
Code-generation rule for properties of types derived from `Component` or `Control`:
430
431
| Approach | Attribute | Use Case | Example |
432
|----------|-----------|----------|---------|
433
| Default value | `[DefaultValue]` | Simple types, no serialization if matches default | `[DefaultValue(typeof(Color), "Yellow")]` |
434
| Hidden | `[DesignerSerializationVisibility.Hidden]` | Runtime-only data | Collections, calculated properties |
435
| Conditional | `ShouldSerialize*()` + `Reset*()` | Complex conditions | Custom fonts, optional settings |
436
437
```csharp
438
public class CustomControl : Control
439
{
440
private Font? _customFont;
441
442
// Simple default - no serialization if default
443
[DefaultValue(typeof(Color), "Yellow")]
444
public Color HighlightColor { get; set; } = Color.Yellow;
445
446
// Hidden - never serialize
447
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
448
public List<string> RuntimeData { get; set; }
449
450
// Conditional serialization
451
public Font? CustomFont
452
{
453
get => _customFont ?? Font;
454
set { /* setter logic */ }
455
}
456
457
private bool ShouldSerializeCustomFont()
458
=> _customFont is not null && _customFont.Size != 9.0f;
459
460
private void ResetCustomFont()
461
=> _customFont = null;
462
}
463
```
464
465
**Important:** Use exactly ONE of the above approaches per property for types derived from `Component` or `Control`.
466
467
---
468
469
## WinForms Design Principles
470
471
### Core Rules
472
473
**Scaling and DPI:**
474
- Use adequate margins/padding; prefer TableLayoutPanel (TLP)/FlowLayoutPanel (FLP) over absolute positioning of controls.
475
- The layout cell-sizing approach priority for TLPs is:
476
* Rows: AutoSize > Percent > Absolute
477
* Columns: AutoSize > Percent > Absolute
478
479
- For newly added Forms/UserControls: Assume 96 DPI/100% for `AutoScaleMode` and scaling
480
- For existing Forms: Leave AutoScaleMode setting as-is, but take scaling for coordinate-related properties into account
481
482
- Be DarkMode-aware in .NET 9+ - Query current DarkMode status: `Application.IsDarkModeEnabled`
483
* Note: In DarkMode, only the `SystemColors` values change automatically to the complementary color palette.
484
485
- Thus, owner-draw controls, custom content painting, and DataGridView theming/coloring need customizing with absolute color values.
486
487
### Layout Strategy
488
489
**Divide and conquer:**
490
- Use multiple or nested TLPs for logical sections - don't cram everything into one mega-grid.
491
- Main form uses either SplitContainer or an "outer" TLP with % or AutoSize-rows/cols for major sections.
492
- Each UI-section gets its own nested TLP or - in complex scenarios - a UserControl, which has been set up to handle the area details.
493
494
**Keep it simple:**
495
- Individual TLPs should be 2-4 columns max
496
- Use GroupBoxes with nested TLPs to ensure clear visual grouping.
497
- RadioButtons cluster rule: single-column, auto-size-cells TLP inside AutoGrow/AutoSize GroupBox.
498
- Large content area scrolling: Use nested panel controls with `AutoScroll`-enabled scrollable views.
499
500
**Sizing rules: TLP cell fundamentals**
501
- Columns:
502
* AutoSize for caption columns with `Anchor = Left | Right`.
503
* Percent for content columns, percentage distribution by good reasoning, `Anchor = Top | Bottom | Left | Right`.
504
Never dock cells, always anchor!
505
* Avoid _Absolute_ column sizing mode, unless for unavoidable fixed-size content (icons, buttons).
506
- Rows:
507
* AutoSize for rows with "single-line" character (typical entry fields, captions, checkboxes).
508
* Percent for multi-line TextBoxes, rendering areas AND filling distance filler for remaining space to e.g., a bottom button row (OK|Cancel).
509
* Avoid _Absolute_ row sizing mode even more.
510
511
- Margins matter: Set `Margin` on controls (min. default 3px).
512
- Note: `Padding` does not have an effect in TLP cells.
513
514
### Common Layout Patterns
515
516
#### Single-line TextBox (2-column TLP)
517
**Most common data entry pattern:**
518
- Label column: AutoSize width
519
- TextBox column: 100% Percent width
520
- Label: `Anchor = Left | Right` (vertically centers with TextBox)
521
- TextBox: `Dock = Fill`, set `Margin` (e.g., 3px all sides)
522
523
#### Multi-line TextBox or Larger Custom Content - Option A (2-column TLP)
524
- Label in same row, `Anchor = Top | Left`
525
- TextBox: `Dock = Fill`, set `Margin`
526
- Row height: AutoSize or Percent to size the cell (cell sizes the TextBox)
527
528
#### Multi-line TextBox or Larger Custom Content - Option B (1-column TLP, separate rows)
529
- Label in dedicated row above TextBox
530
- Label: `Dock = Fill` or `Anchor = Left`
531
- TextBox in next row: `Dock = Fill`, set `Margin`
532
- TextBox row: AutoSize or Percent to size the cell
533
534
**Critical:** For multi-line TextBox, the TLP cell defines the size, not the TextBox's content.
535
536
### Container Sizing (CRITICAL - Prevents Clipping)
537
538
**For GroupBox/Panel inside TLP cells:**
539
- MUST set `AutoSize = true` and `AutoSizeMode = GrowOnly`
540
- Should `Dock = Fill` in their cell
541
- Parent TLP row should be AutoSize
542
- Content inside GroupBox/Panel should use nested TLP or FlowLayoutPanel
543
544
**Why:** Fixed-height containers clip content even when parent row is AutoSize. The container reports its fixed size, breaking the sizing chain.
545
546
### Modal Dialog Button Placement
547
548
**Pattern A - Bottom-right buttons (standard for OK/Cancel):**
549
- Place buttons in FlowLayoutPanel: `FlowDirection = RightToLeft`
550
- Keep additional Percentage Filler-Row between buttons and content.
551
- FLP goes in bottom row of main TLP
552
- Visual order of buttons: [OK] (left) [Cancel] (right)
553
554
**Pattern B - Top-right stacked buttons (wizards/browsers):**
555
- Place buttons in FlowLayoutPanel: `FlowDirection = TopDown`
556
- FLP in dedicated rightmost column of main TLP
557
- Column: AutoSize
558
- FLP: `Anchor = Top | Right`
559
- Order: [OK] above [Cancel]
560
561
**When to use:**
562
- Pattern A: Data entry dialogs, settings, confirmations
563
- Pattern B: Multi-step wizards, navigation-heavy dialogs
564
565
### Complex Layouts
566
567
- For complex layouts, consider creating dedicated UserControls for logical sections.
568
- Then: Nest those UserControls in (outer) TLPs of Form/UserControl, and use DataContext for data passing.
569
- One UserControl per TabPage keeps Designer code manageable for tabbed interfaces.
570
571
### Modal Dialogs
572
573
| Aspect | Rule |
574
|--------|------|
575
| Dialog buttons | Order -> Primary (OK): `AcceptButton`, `DialogResult = OK` / Secondary (Cancel): `CancelButton`, `DialogResult = Cancel` |
576
| Close strategy | `DialogResult` gets applied by DialogResult implicitly, no need for additional code |
577
| Validation | Perform on _Form_, not on Field scope. Never block focus-change with `CancelEventArgs.Cancel = true` |
578
579
Use `DataContext` property (.NET 8+) of Form to pass and return modal data objects.
580
581
### Layout Recipes
582
583
| Form Type | Structure |
584
|-----------|-----------|
585
| MainForm | MenuStrip, optional ToolStrip, content area, StatusStrip |
586
| Simple Entry Form | Data entry fields on largely left side, just a buttons column on right. Set meaningful Form `MinimumSize` for modals |
587
| Tabs | Only for distinct tasks. Keep minimal count, short tab labels |
588
589
### Accessibility
590
591
- CRITICAL: Set `AccessibleName` and `AccessibleDescription` on actionable controls
592
- Maintain logical control tab order via `TabIndex` (A11Y follows control addition order)
593
- Verify keyboard-only navigation, unambiguous mnemonics, and screen reader compatibility
594
595
### TreeView and ListView
596
597
| Control | Rules |
598
|---------|-------|
599
| TreeView | Must have visible, default-expanded root node |
600
| ListView | Prefer over DataGridView for small lists with fewer columns |
601
| Content setup | Generate in code, NOT in designer code-behind |
602
| ListView columns | Set to `-1` (size to longest content) or `-2` (size to header name) after populating |
603
| SplitContainer | Use for resizable panes with TreeView/ListView |
604
605
### DataGridView
606
607
- Prefer derived class with double buffering enabled
608
- Configure colors when in DarkMode!
609
- Large data: page/virtualize (`VirtualMode = True` with `CellValueNeeded`)
610
611
### Resources and Localization
612
613
- String literal constants for UI display NEED to be in resource files.
614
- When laying out Forms/UserControls, take into account that localized captions might have different string lengths.
615
- Instead of using icon libraries, try rendering icons from the font "Segoe UI Symbol".
616
- If an image is needed, write a helper class that renders symbols from the font in the desired size.
617
618
## Critical Reminders
619
620
| # | Rule |
621
|---|------|
622
| 1 | `InitializeComponent` code serves as serialization format - more like XML, not C# |
623
| 2 | Two contexts, two rule sets - designer code-behind vs regular code |
624
| 3 | Validate form/control names before generating code |
625
| 4 | Stick to coding style rules for `InitializeComponent` |
626
| 5 | Designer files never use NRT annotations |
627
| 6 | Modern C# features for regular code ONLY |
628
| 7 | Data binding: Treat ViewModels as DataSources, remember `Command` and `CommandParameter` properties |
629

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…