'Apply StringFormat for every MyTextBox object in WPF/C#

I have MyTextBox class that inherits from WPF TextBox, I am using MyTextBox everywhere in XAML code, I want to update MyTextBox C# class so I ended up with a StringFormat applied over MyTextBox's TextProperty everywhere in UI, so I do not have to update every MyTextBox occurrence in every XAML file.

Note: I have seen something like this but I think it is not proper to reset the binding object twice for every object! I am looking for something more elegant and efficient!

var oldBinding = this.GetBindingExpression(TextProperty)?
                    .ParentBinding;
if (oldBinding != null)
{
    var newBinding = new Binding(oldBinding.Path.Path)
    {
        // copy everything from oldBinding
        StringFormat = "MyStringFormat"
    };
    this.SetBinding(TextProperty, newBinding);
}


Solution 1:[1]

... but I think it is not proper to reset the binding object twice for every object!

Well, since you cannot change a sealed binding that is defined in the XAML markup you actually have to create a new binding and replace the existing one.

The other option is to edit the XAML files and define the correct binding with the StringFormat in the first place.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mm8