Skip to content
defining-wpf-dependencyproperty logo

WPF DependencyProperty Patterns

defining-wpf-dependencyproperty

Defines WPF DependencyProperty with Register, PropertyMetadata, callbacks, and validation. Use when creating custom controls, attached properties, or properties that support data binding and styling.

SKILL.md

Full skill instructions

WPF DependencyProperty Patterns

Defining dependency properties for data binding, styling, animation, and property value inheritance.

Advanced Patterns: See ADVANCED.md for value inheritance, metadata override, and event integration.

1. DependencyProperty Overview

Standard CLR Property:
    private string _name;
    public string Name { get => _name; set => _name = value; }

DependencyProperty:
    public static readonly DependencyProperty NameProperty = ...
    public string Name { get => (string)GetValue(NameProperty); set => SetValue(NameProperty, value); }

Benefits:
    ✅ Data Binding
    ✅ Styling & Templating
    ✅ Animation
    ✅ Property Value Inheritance
    ✅ Default Values
    ✅ Change Notifications
    ✅ Value Coercion
    ✅ Validation

2. Basic DependencyProperty

2.1 Standard Registration

namespace MyApp.Controls;

using System.Windows;
using System.Windows.Controls;

public class MyControl : Control
{
    // 1. Register DependencyProperty
    public static readonly DependencyProperty TitleProperty = DependencyProperty.Register(
        name: nameof(Title),
        propertyType: typeof(string),
        ownerType: typeof(MyControl),
        typeMetadata: new PropertyMetadata(defaultValue: string.Empty));

    // 2. CLR property wrapper
    public string Title
    {
        get => (string)GetValue(TitleProperty);
        set => SetValue(TitleProperty, value);
    }
}

2.2 With FrameworkPropertyMetadata

public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
    name: nameof(Value),
    propertyType: typeof(double),
    ownerType: typeof(MyControl),
    typeMetadata: new FrameworkPropertyMetadata(
        defaultValue: 0.0,
        flags: FrameworkPropertyMetadataOptions.AffectsRender |
               FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
        propertyChangedCallback: OnValueChanged,
        coerceValueCallback: CoerceValue),
    validateValueCallback: ValidateValue);

public double Value
{
    get => (double)GetValue(ValueProperty);
    set => SetValue(ValueProperty, value);
}

3. FrameworkPropertyMetadataOptions

FlagDescription
NoneNo special behavior
AffectsMeasureTriggers Measure pass on change
AffectsArrangeTriggers Arrange pass on change
AffectsRenderTriggers Render on change
InheritsValue inherits to child elements
BindsTwoWayByDefaultDefault binding mode is TwoWay

Common Combinations

// Read-only display property (AffectsRender)
new FrameworkPropertyMetadata(
    defaultValue: null,
    flags: FrameworkPropertyMetadataOptions.AffectsRender);

// Layout-affecting property (AffectsMeasure)
new FrameworkPropertyMetadata(
    defaultValue: 100.0,
    flags: FrameworkPropertyMetadataOptions.AffectsMeasure |
           FrameworkPropertyMetadataOptions.AffectsArrange);

// Two-way bindable property
new FrameworkPropertyMetadata(
    defaultValue: false,
    flags: FrameworkPropertyMetadataOptions.BindsTwoWayByDefault);

4. Callbacks

4.1 PropertyChangedCallback

public static readonly DependencyProperty IsActiveProperty = DependencyProperty.Register(
    nameof(IsActive),
    typeof(bool),
    typeof(MyControl),
    new PropertyMetadata(false, OnIsActiveChanged));

private static void OnIsActiveChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var control = (MyControl)d;
    var oldValue = (bool)e.OldValue;
    var newValue = (bool)e.NewValue;

    // Handle property change
    control.UpdateVisualState(newValue);
}

4.2 CoerceValueCallback

public static readonly DependencyProperty ProgressProperty = DependencyProperty.Register(
    nameof(Progress),
    typeof(double),
    typeof(ProgressControl),
    new FrameworkPropertyMetadata(
        0.0,
        propertyChangedCallback: null,
        coerceValueCallback: CoerceProgress));

private static object CoerceProgress(DependencyObject d, object baseValue)
{
    var value = (double)baseValue;

    // Clamp value to valid range
    if (value < 0.0) return 0.0;
    if (value > 100.0) return 100.0;

    return value;
}

4.3 ValidateValueCallback

public static readonly DependencyProperty CountProperty = DependencyProperty.Register(
    nameof(Count),
    typeof(int),
    typeof(MyControl),
    new PropertyMetadata(0),
    ValidateCount);  // Note: Not part of PropertyMetadata

private static bool ValidateCount(object value)
{
    var count = (int)value;

    // Return false to reject the value (throws exception)
    return count >= 0;
}

4.4 Callback Execution Order

1. ValidateValueCallback - Can reject value (throw exception)
2. CoerceValueCallback   - Can modify value
3. PropertyChangedCallback - Handle the change

5. Read-Only DependencyProperty

namespace MyApp.Controls;

using System.Windows;

public class StatusControl : Control
{
    // 1. Register read-only property key (private)
    private static readonly DependencyPropertyKey IsConnectedPropertyKey =
        DependencyProperty.RegisterReadOnly(
            nameof(IsConnected),
            typeof(bool),
            typeof(StatusControl),
            new FrameworkPropertyMetadata(false));

    // 2. Expose public DependencyProperty
    public static readonly DependencyProperty IsConnectedProperty =
        IsConnectedPropertyKey.DependencyProperty;

    // 3. Read-only CLR property
    public bool IsConnected => (bool)GetValue(IsConnectedProperty);

    // 4. Internal setter using key
    protected void SetIsConnected(bool value)
    {
        SetValue(IsConnectedPropertyKey, value);
    }
}

6. Attached Property

6.1 Defining Attached Property

namespace MyApp.Attached;

using System.Windows;

public static class GridHelper
{
    // Register attached property
    public static readonly DependencyProperty ColumnSpacingProperty =
        DependencyProperty.RegisterAttached(
            name: "ColumnSpacing",
            propertyType: typeof(double),
            ownerType: typeof(GridHelper),
            defaultMetadata: new FrameworkPropertyMetadata(
                0.0,
                FrameworkPropertyMetadataOptions.AffectsMeasure,
                OnColumnSpacingChanged));

    // Getter
    public static double GetColumnSpacing(DependencyObject obj)
    {
        return (double)obj.GetValue(ColumnSpacingProperty);
    }

    // Setter
    public static void SetColumnSpacing(DependencyObject obj, double value)
    {
        obj.SetValue(ColumnSpacingProperty, value);
    }

    private static void OnColumnSpacingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is Grid grid)
        {
            UpdateGridSpacing(grid, (double)e.NewValue);
        }
    }

    private static void UpdateGridSpacing(Grid grid, double spacing)
    {
        // Implementation
    }
}

6.2 Using Attached Property in XAML

<Grid local:GridHelper.ColumnSpacing="10">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </​Grid.ColumnDefinitions>
    <!-- Children -->
</​Grid>

7. References

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View