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

后端 未结 1 1865
栀梦
栀梦 2020-12-04 00:37

I don\'t know the correct wording to describe what I\'m trying to do here... so I\'ll just show it.

This xaml I know works:


  

        
相关标签:
1条回答
  • 2020-12-04 01:11

    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.

    0 讨论(0)
提交回复
热议问题