developing-wpf-customcontrols
Develops WPF CustomControls using Parts and States Model best practices. Use when creating templatable controls with TemplatePart, TemplateVisualState, OnApplyTemplate, or VisualStateManager.
What this skill does
# WPF CustomControl Development - Parts and States Model
Workflow for developing WPF CustomControls with appearance customization capability.
## Development Flow
### 1. Control Inheritance Decision
```
UserControl Selection Criteria:
- Need rapid development
- ControlTemplate customization not required
- Complex theme support not required
Control Inheritance Selection Criteria:
- Need appearance customization via ControlTemplate
- Need various theme support
- Need same extensibility as WPF built-in controls
```
### 2. Define Control Contract
Declare `TemplatePart` and `TemplateVisualState` attributes on the class:
```csharp
[TemplatePart(Name = PartUpButton, Type = typeof(RepeatButton))]
[TemplatePart(Name = PartDownButton, Type = typeof(RepeatButton))]
[TemplateVisualState(Name = StatePositive, GroupName = GroupValueStates)]
[TemplateVisualState(Name = StateNegative, GroupName = GroupValueStates)]
[TemplateVisualState(Name = StateFocused, GroupName = GroupFocusStates)]
[TemplateVisualState(Name = StateUnfocused, GroupName = GroupFocusStates)]
public class NumericUpDown : Control
{
// Define Part/State names as const
private const string PartUpButton = "PART_UpButton";
private const string PartDownButton = "PART_DownButton";
private const string GroupValueStates = "ValueStates";
private const string GroupFocusStates = "FocusStates";
private const string StatePositive = "Positive";
private const string StateNegative = "Negative";
private const string StateFocused = "Focused";
private const string StateUnfocused = "Unfocused";
}
```
### 3. Template Part Property Pattern
Wrap Part elements as private properties, subscribe/unsubscribe events in setter:
```csharp
private RepeatButton? _upButton;
private RepeatButton? UpButtonElement
{
get => _upButton;
set
{
// Unsubscribe from existing element's events
if (_upButton is not null)
_upButton.Click -= OnUpButtonClick;
_upButton = value;
// Subscribe to new element's events
if (_upButton is not null)
_upButton.Click += OnUpButtonClick;
}
}
```
### 4. OnApplyTemplate Implementation
```csharp
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
// GetTemplateChild + as cast (null on type mismatch)
UpButtonElement = GetTemplateChild(PartUpButton) as RepeatButton;
DownButtonElement = GetTemplateChild(PartDownButton) as RepeatButton;
// Set initial state (without transition)
UpdateStates(useTransitions: false);
}
```
**Core Principles:**
- If Part is missing or type differs, it's null → don't cause errors
- Control must work even with incomplete ControlTemplate
### 5. UpdateStates Helper Method
Centralize state transition logic in a single method:
```csharp
private void UpdateStates(bool useTransitions)
{
// ValueStates group
VisualStateManager.GoToState(this,
Value >= 0 ? StatePositive : StateNegative,
useTransitions);
// FocusStates group
VisualStateManager.GoToState(this,
IsFocused ? StateFocused : StateUnfocused,
useTransitions);
}
```
**When to call UpdateStates:**
- `OnApplyTemplate` - Initial state (useTransitions: false)
- Property changed callback - Reflect value change (useTransitions: true)
- `OnGotFocus`/`OnLostFocus` - Focus state (useTransitions: true)
### 6. Property Changed Callback
```csharp
private static void OnValueChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var control = (NumericUpDown)d;
control.UpdateStates(useTransitions: true);
control.OnValueChanged(new ValueChangedEventArgs((int)e.NewValue));
}
```
### 7. ControlTemplate Structure (Generic.xaml)
```xml
<Style TargetType="{x:Type local:NumericUpDown}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:NumericUpDown}">
<Grid Background="{TemplateBinding Background}">
<!-- Place VisualStateGroups on root element -->
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="ValueStates">
<VisualState x:Name="Positive"/>
<VisualState x:Name="Negative">
<Storyboard>
<ColorAnimation To="Red"
Storyboard.TargetName="ValueText"
Storyboard.TargetProperty="(Foreground).(SolidColorBrush.Color)"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
<VisualStateGroup x:Name="FocusStates">
<VisualState x:Name="Focused">
<Storyboard>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="FocusVisual"
Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Unfocused"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<!-- Define Part elements with x:Name -->
<RepeatButton x:Name="PART_UpButton" Content="▲"/>
<TextBlock x:Name="ValueText" Text="{TemplateBinding Value}"/>
<RepeatButton x:Name="PART_DownButton" Content="▼"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
## Checklist
- [ ] Inherit from Control class (not UserControl)
- [ ] Add `ThemeInfo` attribute to AssemblyInfo.cs → See `/configuring-wpf-themeinfo`
- [ ] Declare required Parts with `TemplatePart` attribute
- [ ] Declare states with `TemplateVisualState` attribute
- [ ] Define Part/State names as const strings
- [ ] Subscribe/unsubscribe events in Part property setter
- [ ] Use `GetTemplateChild` + allow null in `OnApplyTemplate`
- [ ] Centralize state transitions with `UpdateStates` helper
- [ ] Place `VisualStateManager.VisualStateGroups` on ControlTemplate root
- [ ] Place default style in Themes/Generic.xaml
- [ ] Call `DefaultStyleKeyProperty.OverrideMetadata` in static constructor
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.