Skip to content

How to add a dependency property

Add this in your custom control:

csharp
public int Min
{
    get { return (int)GetValue(MinProperty); }
    set { SetValue(MinProperty, value); }
}

public static readonly DependencyProperty MinProperty =
    DependencyProperty.Register(nameof(Min), typeof(int), typeof(SpeedoControl), new FrameworkPropertyMetadata(
			0, //Default Value
            new PropertyChangedCallback(OnValueChanged) // automatically called when the value changes
        )
    );

You can use functions which get automatically called

csharp
private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    // cast the sender back to your control
    SpeedoControl control = (SpeedoControl)d;

    int oldValue = (int)e.OldValue;
    int newValue = (int)e.NewValue;

    control.UpdatePointerAngle();
}

You can then bind like this from your xaml

<TextBox Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Min, Mode=TwoWay}"/>

You can also use this to make it automatically a twoWay binding:

new FrameworkPropertyMetadata(
    0,
    FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
    OnMinimumChanged)