Search code examples
c#wpfdata-bindingtextbox

Apply StringFormat from C# code to every custom TextBox


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

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

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!


Solution

  • ... 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.