using-wpf-behaviors-triggers
Implements XAML behaviors and triggers using Microsoft.Xaml.Behaviors.Wpf. Use when adding interactivity to XAML without code-behind, implementing EventToCommand patterns, or creating reusable behaviors.
What this skill does
# WPF Behaviors and Triggers
## 1. Setup
### 1.1 Install NuGet Package
```xml
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.*" />
```
### 1.2 XAML Namespace
```xml
<Window xmlns:b="http://schemas.microsoft.com/xaml/behaviors">
```
---
## 2. EventTrigger
Executes actions when events occur.
### 2.1 InvokeCommandAction (MVVM Recommended)
```xml
<Button Content="Click Me">
<b:Interaction.Triggers>
<b:EventTrigger EventName="Click">
<b:InvokeCommandAction Command="{Binding ClickCommand}"/>
</b:EventTrigger>
</b:Interaction.Triggers>
</Button>
```
### 2.2 With Event Args
```xml
<ListBox>
<b:Interaction.Triggers>
<b:EventTrigger EventName="SelectionChanged">
<b:InvokeCommandAction Command="{Binding SelectionChangedCommand}"
PassEventArgsToCommand="True"/>
</b:EventTrigger>
</b:Interaction.Triggers>
</ListBox>
```
### 2.3 ChangePropertyAction
```xml
<Button Content="Toggle Visibility">
<b:Interaction.Triggers>
<b:EventTrigger EventName="Click">
<b:ChangePropertyAction TargetName="MyPanel"
PropertyName="Visibility"
Value="Collapsed"/>
</b:EventTrigger>
</b:Interaction.Triggers>
</Button>
<StackPanel x:Name="MyPanel"/>
```
---
## 3. DataTrigger
Executes actions based on data conditions.
```xml
<TextBlock Text="{Binding Status}">
<b:Interaction.Triggers>
<b:DataTrigger Binding="{Binding IsLoading}" Value="True">
<b:ChangePropertyAction PropertyName="Text" Value="Loading..."/>
<b:ChangePropertyAction PropertyName="Foreground" Value="Gray"/>
</b:DataTrigger>
<b:DataTrigger Binding="{Binding HasError}" Value="True">
<b:ChangePropertyAction PropertyName="Foreground" Value="Red"/>
</b:DataTrigger>
</b:Interaction.Triggers>
</TextBlock>
```
---
## 4. Custom Behavior
Encapsulates reusable behaviors.
### 4.1 Basic Behavior
```csharp
public sealed class FocusOnLoadBehavior : Behavior<UIElement>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Loaded += OnLoaded;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.Loaded -= OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
AssociatedObject.Focus();
}
}
```
```xml
<TextBox>
<b:Interaction.Behaviors>
<local:FocusOnLoadBehavior/>
</b:Interaction.Behaviors>
</TextBox>
```
### 4.2 Behavior with DependencyProperty
```csharp
public sealed class SelectAllOnFocusBehavior : Behavior<TextBox>
{
public static readonly DependencyProperty IsEnabledProperty =
DependencyProperty.Register(
nameof(IsEnabled),
typeof(bool),
typeof(SelectAllOnFocusBehavior),
new PropertyMetadata(true));
public bool IsEnabled
{
get => (bool)GetValue(IsEnabledProperty);
set => SetValue(IsEnabledProperty, value);
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.GotFocus += OnGotFocus;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.GotFocus -= OnGotFocus;
}
private void OnGotFocus(object sender, RoutedEventArgs e)
{
if (IsEnabled)
{
AssociatedObject.SelectAll();
}
}
}
```
```xml
<TextBox Text="Select me on focus">
<b:Interaction.Behaviors>
<local:SelectAllOnFocusBehavior IsEnabled="{Binding IsSelectAllEnabled}"/>
</b:Interaction.Behaviors>
</TextBox>
```
### 4.3 Drag and Drop Behavior
```csharp
public sealed class DragDropBehavior : Behavior<UIElement>
{
public static readonly DependencyProperty DropCommandProperty =
DependencyProperty.Register(
nameof(DropCommand),
typeof(ICommand),
typeof(DragDropBehavior));
public ICommand? DropCommand
{
get => (ICommand?)GetValue(DropCommandProperty);
set => SetValue(DropCommandProperty, value);
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.AllowDrop = true;
AssociatedObject.Drop += OnDrop;
AssociatedObject.DragOver += OnDragOver;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.Drop -= OnDrop;
AssociatedObject.DragOver -= OnDragOver;
}
private void OnDragOver(object sender, DragEventArgs e)
{
e.Effects = e.Data.GetDataPresent(DataFormats.FileDrop)
? DragDropEffects.Copy
: DragDropEffects.None;
e.Handled = true;
}
private void OnDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
var files = (string[])e.Data.GetData(DataFormats.FileDrop)!;
DropCommand?.Execute(files);
}
}
}
```
```xml
<Border Background="LightGray" MinHeight="100">
<b:Interaction.Behaviors>
<local:DragDropBehavior DropCommand="{Binding FileDroppedCommand}"/>
</b:Interaction.Behaviors>
<TextBlock Text="Drop files here" HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Border>
```
---
## 5. Custom TriggerAction
```csharp
public sealed class ShowMessageAction : TriggerAction<DependencyObject>
{
public static readonly DependencyProperty MessageProperty =
DependencyProperty.Register(
nameof(Message),
typeof(string),
typeof(ShowMessageAction));
public string Message
{
get => (string)GetValue(MessageProperty);
set => SetValue(MessageProperty, value);
}
protected override void Invoke(object parameter)
{
MessageBox.Show(Message, "Information",
MessageBoxButton.OK, MessageBoxImage.Information);
}
}
```
```xml
<Button Content="Show Message">
<b:Interaction.Triggers>
<b:EventTrigger EventName="Click">
<local:ShowMessageAction Message="Hello, World!"/>
</b:EventTrigger>
</b:Interaction.Triggers>
</Button>
```
---
## 6. Common Patterns
### 6.1 Close Window
```xml
<Button Content="Close">
<b:Interaction.Triggers>
<b:EventTrigger EventName="Click">
<b:CallMethodAction TargetObject="{Binding RelativeSource={RelativeSource AncestorType=Window}}"
MethodName="Close"/>
</b:EventTrigger>
</b:Interaction.Triggers>
</Button>
```
### 6.2 Focus Next on Enter
```csharp
public sealed class MoveNextOnEnterBehavior : Behavior<UIElement>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.KeyDown += OnKeyDown;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.KeyDown -= OnKeyDown;
}
private void OnKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
AssociatedObject.MoveFocus(
new TraversalRequest(FocusNavigationDirection.Next));
}
}
}
```
---
## 7. Best Practices
| DO | DON'T |
|----|-------|
| ✅ Implement `OnDetaching` in Behavior (prevent memory leaks) | ❌ Write event handlers directly in code-behind |
| ✅ Follow MVVM pattern (InvokeCommandAction) | ❌ Reference ViewModel directly in Behavior |
| ✅ Make configurable via DependencyProperty | ❌ Use hardcoded values |
| ✅ Design reusable Behaviors | ❌ Behaviors that only work with specific controls |
---
## 8. Related Skills
- `handling-wpf-input-commands` - ICommand, RoutedCommand
- `routing-wpf-events` - Routed Events
- `implementing-wpf-dragdrop` - Drag and Drop
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.