wpfwpf-controlsdependency-propertiesblend

How to add min and max validation for the custom WPF control?


I would like to create a custom control with the multiple WPF dependency properties.

One of the properties is returning Thickness object.

Custom control should be suitable to be also used by designers in the Microsoft Blend.

Blend is allowing properties like Thickness to be limited. For example BorderThickness cannot be less than 0.

How to create custom control with the thickness property where min value is 1 and max 3? I am expecting that also Blend will visually validate data in same way like BorderThickness for the Microsoft default controls.


Solution

  • You can define validation / coerce property callbacks when you register them. This MSDN page has a more detailed description of implementing dependency property validation.

    In short though - you can specify validation and coercion callbacks for any property when you register it and check the thickness value inside of those callbacks.

    For example, here is how the Border's BorderThickness property is registered (code from ILSpy):

    public static readonly DependencyProperty BorderThicknessProperty = 
        DependencyProperty.Register(
            "BorderThickness", 
            typeof(Thickness), 
            typeof(Border), 
            new FrameworkPropertyMetadata(default(Thickness), 
            FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender,
            new PropertyChangedCallback(Border.OnClearPenCache)),
            new ValidateValueCallback(Border.IsThicknessValid));
    

    And here is the validation method itself:

    private static bool IsThicknessValid(object value)
    {
        return ((Thickness)value).IsValid(false, false, false, false);
    }