Skip to content
Back to skills

Gum Tool Variable Grid

ASecurity

Gum Variables tab and DataUiGrid. Triggers: Variables tab, DataUiGrid control, MemberCategory, InstanceMember, category population, property grid refresh, expansion state persistence.

  • 666 stars
  • 0 votes
  • 0 copies
  • 2 views
  • Added November 7, 2026
designgoc#reactnodeawstestinggitbackend

Works with

  • cursor
  • cli

Security analysis

A100/100

Scanned November 24, 2026

npx -y skills add vchelaru/Gum --skill gum-tool-variable-grid --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Gum Tool Variable Grid?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Gum Tool Variable Grid
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/vchelaru-gum-tool-variable-grid/badge)](https://www.skillsdirectory.com/skills/vchelaru-gum-tool-variable-grid)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: gum-tool-variable-grid
description: Gum Variables tab and DataUiGrid. Triggers: Variables tab, DataUiGrid control, MemberCategory, InstanceMember, category population, property grid refresh, expansion state persistence.
---

# Gum Variables Tab & DataUiGrid Reference

## Overview

The **Variables tab** displays and edits properties of the selected element, instance, state, or behavior. The grid's model is framework-neutral in `DataUi.Core` (net10.0: `InstanceMember`, `MemberCategory`, `DataUiGridModel`, `DisplayerRegistry`, and the editor logic classes, still in the `WpfDataUi.*` namespaces). `WpfDataUi` holds only the WPF views (`DataUiGrid`, an `ItemsControl` over a `DataUiGridModel`, plus the editors) and `AvaloniaDataUi` the Avalonia ones (`DataUiGrid.cs`, `SingleDataUiContainer.cs`, editors under `Controls/`, all built in C#); the Avalonia head is the shipped tool, the WPF head is frozen. Categories render as collapsible `Expander` sections.

Headless Variables grid scenarios and their harness: `Tests/Gum.Avalonia.Tests/VariableGrid/README.md`.

> Icons rendered inside the Variables grid (unit selectors, alignment, dock/anchor, origin/sizing toggle-button option displays) come from the `GumIcon`/`PathGeometry` pipeline. For authoring or replacing them see [gum-icons](../gum-icons/SKILL.md).

---

## Architecture Layers

```
[User selects object]
        ↓
[VariableGridPluginBase] (event subscription; each head exports a MainVariableGridPlugin subclass)
        ↓
[PropertyGridManager.RefreshDataGrid()]
        ↓
[ElementSaveDisplayer.GetCategories()]
        ↓ (produces List<MemberCategory>)
[DataUiGrid.SetCategories()]
        ↓
[WPF Expander per MemberCategory, rows per InstanceMember]
```

---

## Key Files

| Purpose | File Path |
|---------|-----------|
| Grid logic (categories, filter, expansion memory, multi-select) | `DataUi.Core/DataUiGridModel.cs` |
| Editor choice (preferred displayer, custom options, type, text) | `DataUi.Core/DisplayerRegistry.cs`, keys in `DataUi.Core/DataTypes/StandardDisplayers.cs` |
| WPF DataUiGrid control (renders the model) | `WpfDataUi/DataUiGrid.cs` |
| DataUiGrid XAML template | `WpfDataUi/Themes/Generic.xaml` |
| Avalonia DataUiGrid control and row host | `AvaloniaDataUi/DataUiGrid.cs`, `AvaloniaDataUi/SingleDataUiContainer.cs` |
| Avalonia editors | `AvaloniaDataUi/Controls/SimpleDisplays.cs`, `CompositeDisplays.cs`, `TextBoxDisplay.cs` over `DataUiDisplayBase` |
| Avalonia drag/scrub capture (ends once on release or capture loss) and wheel-ignoring closed combo | `AvaloniaDataUi/Controls/CapturedPointerDrag.cs`, `WheelIgnoringComboBox` in `SimpleDisplays.cs` |
| MemberCategory / InstanceMember models | `DataUi.Core/DataTypes/` |
| Gum-specific member subclass | `Tools/Gum.Presentation/PropertyGridHelpers/StateReferencingInstanceMember.cs` |
| Plugin wiring selection events | `Tools/Gum.Presentation/Plugins/InternalPlugins/VariableGrid/VariableGridPluginBase.cs` (each head exports a `MainVariableGridPlugin` subclass) |
| Category population manager | `Tools/Gum.Presentation/Plugins/InternalPlugins/VariableGrid/PropertyGridManager.cs` |
| Category factory | `Tools/Gum.Presentation/Plugins/InternalPlugins/VariableGrid/ElementSaveDisplayer.cs` |
| Behavior categories | `Tools/Gum.Presentation/Plugins/InternalPlugins/VariableGrid/BehaviorShowingLogic.cs` |
| What a head supplies (tab view, Gum displayer controls) | `IVariableGridHead` / `IVariablesTabView`; `Gum/.../VariableGrid/WpfVariableGridHead.cs` and `Tool/Gum.Avalonia/Plugins/VariableGrid/` |
| WPF host UserControl | `Gum/Plugins/InternalPlugins/VariableGrid/MainPropertyGrid.xaml(.cs)` |
| Composite member model | `DataUi.Core/DataTypes/CompositeInstanceMember.cs` |
| Composite descriptor registry | `Tools/Gum.Presentation/Plugins/InternalPlugins/VariableGrid/CompositeMemberRegistry.cs`, `CompositeMemberDescriptor.cs`, `CompositeMemberLogic.cs` |

The controller, the row adapter, the composites, and the standard-element displayer setup are all headless in `Gum.Presentation`; the heads only render. `PropertyGridManager` talks to the grid through `IDataUiGrid` and to the view through `IVariablesTabView`, which it gets from the head's `IVariableGridHead`. Gum-specific editors are named by `GumDisplayers` keys (units, alignment, origin toggles, color, corner radius, remove button); each head registers its controls for them (WPF in the static `SingleDataUiContainer.DisplayerRegistry`, Avalonia in `AvaloniaVariableGridHead.Displayers`). What those editors show is shared too: the toggles' options and icons come from `VariableGridToggleOptions` (including the standard-element exclusions for width units, height units, and Y origin) and the corner-radius field logic from `CornerRadiusDisplayLogic`, so change options there, never in a head's control.

Numeric drag-scrub reports every intermediate tick as `VariablePropertyCommitType.Intermediate` and only the mouse-up as `.Full` (`SetVariableLogic.ReactToPropertyValueChanged`'s `isFullCommit` param) — an expensive per-set side effect (e.g. font regeneration) must gate on `Full`, not fire per-tick; see `GraphicalUiElement.SuppressFontRegeneration`. The variable reference cascade (`VariableReferenceLogic.DoVariableReferenceReaction`) also waits for `Full`, so a drag editor must end with a `Full` commit on release and on pointer-capture loss, or the followers stay stale.

---

## Deleting a Custom Variable

`DeleteVariableService` (`Tools/Gum.Presentation/Plugins/InternalPlugins/VariableGrid/DeleteVariableService.cs`) handles the right-click delete; the rules and the data change are in `VariableRemovalLogic` (`Tools/Gum.ProjectServices/Editing/`), shared with `gumcli edit`. It blocks when the variable is referenced through a `VariableReferences` binding, or when an inheriting element exposes a *different* inner variable under the same name. An instance-level value elsewhere in the project, or an inheriting element's own value for the variable, is instead cascaded through `InstanceOverrideRemover`: removed there too, and recorded via `IUndoManager.RecordCrossElementVariableChanges` so undo restores it there as well. See ADR 0016 and the `gum-tool-undo` skill's cross-element exception.

---

## Non-Obvious Behaviors

### SetCategories Expansion Preservation

`DataUiGridModel.SetCategories()` captures `{name → IsExpanded}` from existing categories, replaces the list, then re-applies the saved values by name. Category collapse state persists across selection changes within a session. `IsExpanded` is `Mode=TwoWay` in the XAML template so user gestures write back to the model immediately.

Landmine: the backing `_expansionStates` dictionary is **static** and keyed only by category name, so every `DataUiGrid` in the tool shares one expansion memory and same-named categories in different grids overwrite each other. Anything that expands a category programmatically must keep that out of the dictionary, or it persists as the user's preference for every later selection.

### Detail Text Links

A reference-driven row's "Set by Other.X" names its source as a link: `VariableReferenceLinkLogic` (headless) builds an `InstanceMember.DetailLink` for plain variable paths only, and `DataUiDisplayBase.RefreshHint` draws it. The same class builds `InstanceMember.DetailAction` (Unlink, drawn as the Delete icon via the head's `DataUiDisplayBase.DetailIconFactory`; only when the selected state's own list holds the line), which comments the line out through `ISetVariableLogic.PropertyValueChanged`; the view appends it to the first line of the text. Hit-test links with `CharacterHit.FirstCharacterIndex`, not `TextPosition` (which counts a character's right half as the next one). Landmine: a read-only row disables its content, hint included, and a disabled control gets no pointer events, so the click is handled on the displayer itself (`HandleHintPointerPressed`), not on the hint's `TextBlock`.

### Leftover Variables

`VariableSaveLogic.GetIfVariableIsActive` hides variables the element's or instance's type does not define. Since #7191 a base type change deletes them (`BaseTypeVariablePruner`), so only projects saved by an earlier Gum still hold hidden leftovers; keep the hiding for those.

### Hiding a Row

A row is hidden by removing it from `category.Members`, not by a visibility flag — see `DataUiGridModel.RefreshDelegateBasedElementVisibility`. Row striping stays correct because removed rows no longer count toward `AlternationIndex`. Removal loses the row's position though, and that method re-adds with `Add` (appending), so anything that restores rows needs its own ordered snapshot: `MemberCategoryFilter` (`DataUi.Core/MemberCategoryFilter.cs`) does this for the Variables tab filter box, and `DataUiGridModel.ApplyMemberFilter` re-applies its predicate after every `SetCategories`.

Emptying a category hides its header only because each category `DataTemplate` binds the `Expander`'s `Visibility` to the neutral `MemberCategory.IsVisible` bool (computed from `Members.Count`) through a `BooleanToVisibilityConverter`. Those templates are the three `MemberCategory` `DataTemplate`s in `Gum/Themes/Frb.Styles.Defaults.xaml` and `WpfDataUi/Themes/Generic.xaml` — a new one that omits the binding leaves empty headers stacked on screen, with nothing in the model to indicate the mistake.

### Paired Rows (X/Y, Width/Height, texture rectangle, gradient points)

Avalonia only. `DataUiGrid.RowPairs` (the Variables tab sets `VariableGridRows.Pairs`) shows two members side by side, and it is purely a view concern: `category.Members` stays flat, so the filter, lookups by name, multi-select and copy/paste see ordinary rows. `RowProjection` folds a pair into one row at the first member's place, and `PairedRowView` hosts two ordinary rows, each framed by `RowDecorator`, so each cell keeps its own set-value marker and detail text. It stacks the cells when `DataUiDisplayBase.CompactMinimumWidth` says both cannot fit. Nullable members (the Min/Max sizes) stay out of pairs because their "Is Null" box needs the room.

### Structural Rebuild vs. Partial Refresh

`PropertyGridManager.RefreshDataGrid` tracks the previous display target (element, state, instances, behavior). If unchanged and `force=false`, it calls `Refresh()` to update values without recreating categories. If the target changed, it calls `SetCategories` with a fresh list from `ElementSaveDisplayer`. Pass `force: true` to always rebuild.

Landmine: `SetCategories` is not the only way the grid's categories change. `PropertyGridManager.ReconcileCategories` retargets, swaps (`RemoveAt` plus `Insert`), appends, and drops categories **one at a time** on the live `Categories` collection, so it fires `Add`/`Remove` and never the `Reset` that `SetCategories` produces. Anything deriving state from the category list has to handle both shapes — hooking `SetCategories` alone leaves the state stale after an ordinary selection change, with no error anywhere.

### Control Recycling (SingleDataUiContainer)

WPF only. The Avalonia grid does not pool: rows are rebuilt (Avalonia editors are cheap) and a displayer re-bound to a new member resets its per-member state, which is what the pooling fix below requires anyway. In WPF, `SingleDataUiContainer` maintains a static `Dictionary<Type, Stack<UserControl>>` pool. When a container is removed from the visual tree (`Unloaded`), its inner displayer control is detached and pushed onto the type-keyed stack. When a new container needs a displayer, `CreateInternalControl` first checks if the existing control already matches the needed type (reuse in-place — preserves focus), then tries the pool via `TryGetFromPool`, and only falls back to `Activator.CreateInstance` if both miss. Pooled controls must clean up stale state when reassigned to a new `InstanceMember` (e.g., `TextBoxDisplay` detaches old event handlers, resets error/multiline state, and calls `Refresh`). `SetCategories` uses `BulkObservableCollection.ReplaceAll` (single `Reset` notification) which triggers WPF to unload old containers (returning controls to the pool) and create new ones (pulling from the pool).

### Multi-Select Path

When multiple instances are selected, `SetMultipleCategoryLists` is used instead of `SetCategories`. `MultiSelectInstanceMember` wrappers set every wrapped row in a loop; `MultiSelectCommitLogic` (`Tools/Gum.Presentation/.../VariableGrid/`) marks the rows `IsCallingRefresh = false` and does the undo record and the structural refresh (`ISetVariableLogic.RefreshInResponseToVariableChange`) once per batch.

Landmine: a commit that rebuilds the grid detaches its own editor, and that editor's focus-loss handler then commits again from inside the first commit. `IDataUiExtensionMethods.TrySetValueOnInstance` skips a commit from an editor whose own commit is still running; without that skip, a nested multi-select commit overwrites `MultiSelectCommitLogic`'s single stored undo lock and leaks the first one, which stops undo recording for the rest of the session.

Landmine: `IsCallingRefresh = false` only defers the grid/tree rebuild and undo. Everything else in `VariableGridEntry.NotifyVariableLogic` → `SetVariableLogic.ReactToPropertyValueChanged` (autosave, plugin `VariableSet`, codegen) still runs once per selected instance, so a new per-set side effect added there runs N times on a multi-select edit unless it is gated on `IsCallingRefresh` or moved into the batch.

Landmine: a multi-select edit runs the whole set pipeline once per selected instance, and each pass asked for a grid rebuild (a `VariableReferences` edit asked twice: the line expansion's `RefreshVariables(force)` and the grid plugin's `VariableSet` handler), about 0.7 s each on 19 Rectangles. `MultiSelectCommitLogic` opens `IPluginManager.BeginVariableSetBatch`; while it is open `VariableGridPluginBase` defers those rebuilds (and `PropertyGridManager` the value refresh) and does one when `VariableSetBatchCompleted` fires. A new plugin reaction that covers the whole element must do the same (`PluginBase.IsVariableSetBatchOpen`). To find where an edit's time goes, run the tool with `GUM_TOOL_LOG=<absolute path>` (`Gum.Diagnostics.ToolLog`: timed stages, plugin callbacks of 1 ms or more, flushed per line, off and free otherwise) and add a `ToolLog.Begin` around the suspect stage.

### StateReferencingInstanceMember

All members in the Variables tab use `StateReferencingInstanceMember` (subclass of `InstanceMember`), not the generic reflection path. Its `IsReadOnly` returns `true` when `InstanceSave?.Locked == true`. Its `IsDefault` returns `true` when the value is absent from the selected state (not inherited from defaults).

---

## Custom Displayers (how a variable gets non-default UI)

Most variables render with a default control inferred from their type. A variable gets a *different* control — slider, angle dial, alignment/origin toggles, parent dropdown — through three knobs on `InstanceMember`:

- **`PreferredDisplayer`** (a `Type`) — selects which control renders the row. Neutral code assigns a key type (`StandardDisplayers.Slider`, ...) that each head's `DisplayerRegistry` resolves to its own control; a concrete WPF control type still works inside the WPF head. The row host (`SingleDataUiContainer`) instantiates the resolved control.
- **`PropertiesToSetOnDisplayer`** (a `Dictionary<string, object>`) — after the control exists, the container *reflectively* sets each named property on it. A slider's `MinValue`/`MaxValue` (the "range") are just two such pushes onto a control already chosen by `PreferredDisplayer` — they do **not** create the slider on their own.
- **`UiCreated` event** — for config that must be computed per-instance instead of a constant (see `MakeDegreesAngle`, and the WpfDataUi sample's per-character `MaxValue`).

Gum's built-in variables are wired in `Tools/Gum.Presentation/Plugins/InternalPlugins/VariableGrid/StandardElementsManager.GumTool.cs` (slider for color channels, angle dial, alignment, origin, parent dropdown), as neutral `StandardDisplayers`/`GumDisplayers` keys. That file is where to look or add.

> Naming trap: `MinWidth`/`MaxWidth`/`MinHeight`/`MaxHeight` in `StandardElementsManager.cs` are real runtime layout clamps — unrelated to a displayer's slider `MinValue`/`MaxValue`.

The icon-based displayers (origin/alignment/dock toggles) get their glyphs from the `GumIcon` pipeline — see [gum-icons](../gum-icons/SKILL.md). **A new toggle-button strip gets an icon on every option (`GumIconName` in `VariableGridToggleOptions`), like every existing strip; do not ship text-only buttons.** Load `gum-icons` before adding the option set. The Font drop-down lists installed families through `IInstalledFontProvider` (SkiaSharp on every OS).

**Landmine: a new custom `IDataUi` displayer must wire its own right-click menu and default-value highlighting — nothing does either for you.** `SingleDataUiContainer`/`DataUiGrid` never touch `ContextMenu` or background color. Every existing displayer (`ColorDisplay`, `SliderDisplay`, `TextBoxDisplay`, ...) attaches a WPF `ContextMenu` to its root element in XAML and calls `this.RefreshContextMenu(yourRoot.ContextMenu)` from `Refresh()` — skip it and `InstanceMember.ContextMenuEvents` (Make Default, Copy Qualified Variable Name, expose/un-expose) silently never reach an actual menu; right-click does nothing. Default-value background tinting (driven by `InstanceMember.ValueState`; the WPF brushes are `DataUiBrushes.DefaultValueBackground` / `IndeterminateValueBackground`) is likewise opt-in per displayer — copy the pattern from `WpfDataUiTextBox.ApplyValueState`, don't assume a new control gets it for free. Both gaps compile fine and only show up as "this row behaves differently from every other row" in manual testing.

Same opt-in-per-displayer trap for click-drag-over-label-to-scrub a numeric value: the value math is `LabelDragScrubLogic` (`DataUi.Core/Controls/`), wired by `TextBoxDisplay` (`EnableLabelDragValueChange`, `LabelDragValueRounding`/`LabelDragChangeMultiplier`), not by `DataUiGrid`/`SingleDataUiContainer`. The view feeds it relative pointer deltas from pointer capture; nothing warps the cursor. A custom or composite displayer gets no drag-scrub on its fields unless it drives the same logic.

---

## Composite Members (several variables, one row)

A separate mechanism from `PreferredDisplayer` above: `CompositeMemberLogic.Apply` runs after categories are built and collapses a fixed set of sibling "channel" `InstanceMember`s into a single `CompositeInstanceMember` row, driven by an `IDataUi` control bound to one composed value (not a raw variable). The registered descriptors, all in `CompositeMemberRegistry`, are color (`Red`/`Green`/`Blue` → one swatch row, key `GumDisplayers.Color`), corner radius, and the two NineSlice per-side rows (border scale and source cut), which share `NineSliceSidesComposite` and the Avalonia `NineSliceSidesDisplay`. A new value-plus-four-overrides row reuses `LinkedOverridesDisplay`; register a control for each new key in each head.

Landmine: `CompositeMemberLogic.GroupTriples` matches channels by finding the **first channel's root name as a literal substring** inside a candidate member's root name, splitting off the prefix/suffix, then requiring every other `ChannelRootNames` entry to exist verbatim at that same prefix/suffix. **All channels must be present as real, non-excluded `VariableSave`s in the same category** (mind `MinimumGumxVersion` gating in `ShapeVariableVersionGate.cs`) — if even one is missing, no composite forms and the rest render as ordinary individual rows, silently, with no error.

Landmine: `CompositeInstanceMember.HandleCustomSet` writes **every** channel on every commit, but skips a channel whose decomposed value already equals its current value — this guard matters. It's harmless to omit for Color (an edit there is always "set all of R/G/B explicitly"), but a composite whose channels carry inherit-vs-explicit semantics via nullability (e.g. corner radius's per-corner overrides, where `null` means "inherit the uniform value") would otherwise force-write `null` onto every hidden/untouched channel on every commit, silently flipping it from inherited to explicitly-set and corrupting `IsDefault` bookkeeping for a value nobody touched. "Linked vs. unlinked" for such a composite isn't a stored flag either — it's derived purely from whether the override channels currently resolve to null, recomputed from `ChannelMembers` on every `Compose`.

### Shader Parameter Rows: Expose

A scalar shader parameter row (`VariableGridEntry.ShaderBinding`) is not saved until something names it, so `VariableGridEntry.ExposeVariable` first adds a marked `SetsValue = false` placeholder (`ShaderParameterVariableBinding.AddNamedPlaceholder`) because `ExposeVariableService` and `ObjectFinder.GetRootVariable` only find saved entries. It removes the placeholder again if the name prompt is cancelled. The generated exposed property is write-only and goes through `SetProperty` (`CodeGenerator`, `isShaderParameter`), since the runtime has no property of that name.

---

## Category Copy/Paste (whole-group values)

Right-clicking a category header offers Copy Values / Paste Values (#4455). The gather/apply logic is headless: `VariableCategoryCopyPasteService` in `Tools/Gum.Presentation/.../VariableGrid/`, fed by `IVariableCategoryRow` rows that `VariableCategoryRowAdapter` wraps around the grid's `InstanceMember`s (both headless in `Tools/Gum.Presentation/.../VariableGrid/`). Paste only applies to the category the values were copied from, records as one undo (single `RequestLock` across all writes), and skips rather than fails: absent variables, read-only/reference-assigned rows, type mismatches (numeric mismatches convert), and state names the target doesn't declare.

Category-header menus are `MemberCategory.ContextMenuItems` (`MemberCategoryContextMenuItem` is its own `ICommand`), rendered by the header template in `Frb.Styles.Defaults.xaml`. Landmines:

- **`DataUiGridModel.SetMultipleCategoryLists` copies only `Name` and `HeaderColor`** onto the fresh `MemberCategory` objects it creates for multi-select — any other category-level state (`ContextMenuItems`, `HideHeader`, `Width`) is silently dropped. `PropertyGridManager.RefreshCategoryContextMenus` re-populates after every refresh (guarded to only fill empty categories) for exactly this reason.
- **A `ContextMenu` on a shared template reaches every grid.** The header template serves all `DataUiGrid`s (Code tab, project properties, behaviors), and even a visually-collapsed empty menu still opens and takes mouse capture, eating the next click. Suppress with `ContextMenuService.IsEnabled=False` (via DataTrigger on item count), not `Visibility`.
- **`Type.IsInstanceOfType` is always false against `Nullable<T>`** for a boxed value — variables declared `int?`/`float?` (`MaxLettersToShow`, `MinWidth`, ...) need `Nullable.GetUnderlyingType` before any reflection type gate.
- **A state name is just a string** — any automated write to a state row (`State`, `<Category>State`) must validate against the row's `CustomOptions`/available states or it saves a dangling state name that renders as a blank combo.
- **Write units before values.** Setting `XUnits`/`WidthUnits`/... can convert the target's current `X`/`Width` ("convert variables on unit type change"), so a value written before its unit gets converted away.
- **`MultiSelectInstanceMember.Value` returns null when the wrapped instances disagree** (indeterminate) — indistinguishable from "unset" by value alone; check `IsIndeterminate` before treating null as absent.
- Right-clicking inside a value text field can pop an empty-looking white box (#4457): the native text-editing menu, unthemed — disabled Cut/Copy/Paste entries render invisibly faint, so with no selection and an empty clipboard the menu looks blank. Pre-existing on main; don't chase it as a regression of grid work.

---

## Refresh Trigger Flow

```
Selection changed
  → VariableGridPluginBase.Handle*Selected()
  → PropertyGridManager.RefreshEntireGrid(force: true)
  → RefreshDataGrid(...)
     ├─ Target changed?
     │   yes → ElementSaveDisplayer.GetCategories()
     │          → DataUiGrid.SetCategories()     ← preserves IsExpanded by name
     └─ Target same?
             → DataUiGrid.Refresh()              ← only updates member values
```

### Double-Refresh Guard (Instance Selection)

When an instance is selected, two events fire in sequence: the default state is force-selected first (via `PerformAfterSelectInstanceLogic`), then the instance-selected event fires. Without a guard, the grid rebuilds twice.

```
Selection changed (instance)
  → HandleStateSelected()       (state force-selected first)
  → RefreshEntireGrid(force: true) + the selection coordinator notes the instance
  → HandleInstanceSelected()    (fires second)
  → ShouldRefreshOnInstanceSelected is false → skip redundant refresh
```

`VariableGridSelectionCoordinator` (`Tools/Gum.Presentation/Plugins/InternalPlugins/VariableGrid/`, headless and unit-tested) owns that state; `HandleElementSelected` and `HandleTreeNodeSelected` reset it so it does not suppress legitimate refreshes during unrelated selections.

Variable set by UI:
```
InstanceMember.AfterSetByUi
  → StateReferencingInstanceMember.NotifyVariableLogic()
  → PropertyGridManager.RefreshEntireGrid(force: false)
  → DataUiGrid.Refresh()   (no structural rebuild needed)
```

### Post-set Selective Refresh (`SetVariableLogic`)

After a variable is set, `SetVariableLogic.RefreshInResponseToVariableChange` decides whether the grid needs a structural rebuild, a value-only refresh, or nothing. By default *nothing happens* — most variable edits only need the value-only refresh that already ran upstream. The decision rule is:

1. **Hardcoded name in `VariablesRequiringRefresh` dictionary** (e.g. `Parent`, `BaseType`, `Font`, `TextureAddress`) — these change which other variables exist on the grid, so they trigger a `FullGridRefresh` (rebuild + tree view) or `FullGridValueRefresh` per the dictionary entry.
2. **State variable on the element or an instance** (detected dynamically via `SetVariableLogic.IsStateVariable` → `VariableSave.IsState`) — assigning a categorized state doesn't add/remove variables, but it does change which rows are reference-driven, their `IsDefault` status, and their subtext. Those are computed at category-build time, so a value-only refresh isn't enough → `RefreshVariables(force: true)`.

State variables can't be in the hardcoded dictionary because their names are dynamic (`<CategoryName>State`). Use `IsStateVariable(unqualifiedMember, parentElement, instance)` rather than string-matching.

The trailing-else branch of the dictionary-handling block (`RefreshVariables(force: true)`) is the "rebuild grid, don't touch the tree" path. It's not named in the `VariableRefreshType` enum — it's the fallthrough behavior. Watch for it when reading the code.

---

## Common Patterns

### Making a category collapsed by default

Set `IsExpanded = false` on the `MemberCategory` before passing to `SetCategories`. The first time the category appears it uses the incoming value; subsequent appearances restore the user's last state.

### Forcing a full grid rebuild

Call `PropertyGridManager.RefreshEntireGrid(force: true)`. The `force` flag bypasses the same-target optimization and always recreates categories.

### Writing a variable's `DetailText` (the grid help blurb)

A `VariableSave.DetailText` renders as the help text under that variable in the Variables tab. It is **end-user authoring help shown inside the running tool**, so write it from the tool user's perspective and keep it to what they're choosing right now. Three recurring mistakes when adding a standard variable in `StandardElementsManager`:

- **Keep it to one short line that states the effect.** No "When true", no restating the variable's name, no examples or explanation the docs page covers. A needed warning (such as "Overrides Source File.") stays; everything else goes.
- **Don't restate a visibility condition the exclusion logic already enforces.** If the variable is hidden unless some other variable is set (via `ExclusionsPlugin`), the user only ever sees it when that condition holds — "only used when X is checked" is redundant noise.
- **Don't leak runtime/integration/implementation details the tool user neither sees nor controls** — e.g. "requires a consumer-registered resolver," codegen specifics, or platform backends. Those belong in code-side XML docs or the runtime skill, not in tool UI help. (`SourceShaderFile` originally carried both mistakes because the text was lifted from the runtime/issue framing.)

### Version gate

`ElementSaveDisplayer` hides a standard variable when the project `Version` is older than the variable's `MinimumGumxVersion` tag in `StandardElementsManager`, for every standard element type (`ShapeVariableVersionGate`, which also keeps a legacy name map and keeps `Stroke*`/`Blend` visible). Tagging a new standard variable is all it takes; there is no grid-side list.

### Shader parameter rows

`PropertyGridManager.AdjustShaderParameters` replaces the `ShaderParameters` text row with one row per parameter the compiled shader declares. A single valued parameter gets a normal `VariableGridEntry` over the real saved variable `Instance.<shader file stem>_<Parameter>` (`ShaderVariableNaming`): `VariableGridEntry.ShaderBinding` (a `ShaderParameterVariableBinding`) types and marks the first write, shows the compiled default while nothing is saved (an untouched row saves nothing), and treats a value still in the legacy text as set until the row is edited (that parameter then leaves the text) or made default. `GridName` keeps the member named by the plain parameter name. A float vector is ONE composite row (`ShaderVectorRow.Create`, a `CompositeInstanceMember` named `Tint`, displayer key `GumDisplayers.ShaderVector`) over its component members (`ChannelMembers`, `Tint X` by `GridName`, labeled `X` by `DisplayName`), each over its own variable `Instance.<stem>_Tint__X` with a component binding. The Avalonia `ShaderVectorDisplay` hosts one compact `TextBoxDisplay` per component (letter left of the field, like Width/Height; the fields wrap to a second line when the label column cannot shrink further) and gives every field the row's menu. The composite is not built by `CompositeMemberLogic`, so no channel-name grouping applies. Writing one component saves all of them as one undo step (`PinComponents`: siblings take their current value, else the legacy text, else the compiled default; in a category state they go into that state). The row's Make Default (`ShaderVectorRow`, one undo lock) clears the whole parameter through a component's reset (`ResetOtherComponents` removes the other components, `RemoveLegacyValue` the legacy text), and the row is default only while no component is saved or in the legacy text. A file with only some components saved still loads (the row shows as set) and the first edit saves the rest. The row has no Expose item yet: whole-vector expose (N exposures, one prompt, one grouped `VectorN` property in codegen) is the rest of #7519, and the per-component expose code in `VariableGridEntry.ExposeVariable` is reachable only from tests until it replaces that path. A multi-selection has no shader rows. These rows are added after `CompositeMemberLogic` runs, so a composite never groups them. Parameters with no shader file, an unsupported name, or a non-float vector stay on `ShaderParameterRows` over the text.

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in design →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.