Search code examples
c#wpfxamlbindingmarkup-extensions

Encapsulating repetitive binding parameters in Xaml


I hope this is a duplicate, but I seem to be having searchers block...


In WPF forms, I'm finding myself repeatedly specifying a consistent set of Binding parameters via a lot of cut/paste, e.g.:-

<dxe:TextEdit EditValue="{Binding Name, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" />

...

<dxe:TextEdit EditValue="{Binding Days, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" />

What's the cleanest way to define a markup extension (or something equivalent but more appropriate) which allows me to remove the boilerplate and be able to replace that with e.g.:

<dxe:TextEdit EditValue="{mine:EditorBinding Name}" />

...

<dxe:TextEdit EditValue="{mine:EditorBinding Days>" />

For bonus points, it would be nice to still be able to override the established default for the 5% of cases where that is necessary [but if something small can accomplish the core goal cleanly with minimal fuss, that'll do nicely either...]


Solution

  • You could simply create a derived Binding class, because Binding is already derived from MarkupExtension.

    public class EditorBinding : Binding
    {
        public EditorBinding()
        {
            UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            ValidatesOnDataErrors = true;
            NotifyOnValidationError = true;
        }
    
        public EditorBinding(PropertyPath path)
            : this()
        {
            Path = path;
        }
    }