Can you use a Binding ValidationRule within 1 line in xaml?

Even though the xaml interpreter happens to turn the markup extension into something working, this is not really supported.

See MSDN – Binding Markup Extension

The following are properties of Binding that cannot be set using the Binding markup extension/{Binding} expression form.

  • ValidationRules: the property takes a generic collection of ValidationRule objects. This could be expressed as a property element in a Binding object element, but has no readily available attribute-parsing technique for usage in a Binding expression. See reference topic for ValidationRules.

However, let me suggest a different approach: instead of nesting the custom markup extension in the binding, nest the binding in a custom markup extension:

[ContentProperty("Binding")]
[MarkupExtensionReturnType(typeof(object))]
public class BindingEnhancementMarkup : MarkupExtension
{
    public BindingEnhancementMarkup()
    {

    }
    public BindingEnhancementMarkup(Binding binding)
    {
        Binding = binding;
    }

    [ConstructorArgument("binding")]
    public Binding Binding { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        Binding.ValidationRules.Add(new NotEmptyValidationRule());
        return Binding.ProvideValue(serviceProvider);
    }
}

And use as follows:

<TextBox Text="{local:BindingEnhancementMarkup {Binding Path=Location, UpdateSourceTrigger=PropertyChanged}}"/>

Ofcourse, for production you may want to add a few more checks in the markup extension instead of just assuming everything is in place.

Leave a Comment