DEV Community

Cover image for [Showoff] Tired of DependencyProperty boilerplate? I built a Zero-Allocation Source Generator for WPF/MAUI with strict type safety.
kassyi
kassyi

Posted on

[Showoff] Tired of DependencyProperty boilerplate? I built a Zero-Allocation Source Generator for WPF/MAUI with strict type safety.

Hey everyone,

Let's face it: writing DependencyProperty in .NET UI frameworks is a chore. Typing out DependencyProperty.Register with 20 lines of boilerplate for a single property is tedious, error-prone, and severely clutters your codebase.

I wanted a frictionless DX, so I built a highly optimized Source Generator: Kassyi.Generators.DependencyProperty.

GitHub: Kassyi/DependencyPropertyGenerator
NuGet: Kassyi.Generators.DependencyProperty

1. The Highlights (What makes this different?)

  • 1-Line Generation: Just add [DependencyProperty<T>]. It generates the DP, properties, and callback registrations automatically.
  • Zero IDE Lag (Zero-Allocation): Completely eliminates Gen2 GC spikes during code generation. (More on this below).
  • Bulletproof Type Safety: Catch signature mismatches in your callbacks instantly at compile-time (DPG0001), completely eliminating silent runtime errors.
  • Framework Agnostic: Write the exact same attribute syntax for WPF, MAUI, Avalonia, Uno, WinUI 3, and UWP.

2. Show me the code

Instead of the usual DependencyProperty.Register nightmare, you only write this:


Before (The Boilerplate):

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

public bool IsActive
{
    get => (bool)GetValue(IsActiveProperty);
    set => SetValue(IsActiveProperty, value);
}

private static void OnIsActiveChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ... }

Enter fullscreen mode Exit fullscreen mode

After:

[DependencyProperty<bool>("IsActive", DefaultValue = "false")]
public partial class MyControl : Control
{
    // QoL Feature: The generator automatically detects methods named "On{Prop}Changed" 
    // and magically hooks them up to the PropertyMetadata under the hood!
    partial void OnIsActiveChanged(bool oldValue, bool newValue