Search code examples
wpfbindingpropertiesstring-formattingupdatesourcetrigger

WPF Data Binding with StringFormat when UpdateSourceTrigger is PropertyChanged


I want to have a textbox append a specific string once the user tabs out of the control, i.e. LostFocus, however I prefer the textbox to validate as the user types, so UpdateSourceTrigger is set to PropertyChanged.

Is there a way to get this to work in WPF?

Looked at this question which is similar but wondering if there is a cleaner solution?

My XAML is:

    <TextBox Text="{Binding Path=MyBindingPath, 
                            StringFormat='\{0} -HELLO',
                            TargetNullValue={x:Static sys:String.Empty},
                            ValidatesOnDataErrors=True,   
                            NotifyOnValidationError=True,    
                            UpdateSourceTrigger=PropertyChanged}"/>

Solution

  • You can set UpdateSourceTrigger to Explicit and in the TextChanged event handler of the TextBox you can call UpdateSource explicitly after performing the things you want.

    //write the code you want to run first and then the following code
    BindingExpression exp = this.textBox1.GetBindingExpression(TextBox.TextProperty);
    exp.UpdateSource();