Search code examples
c#.netwpfdata-bindingtextbox

EndEdit equivalent in WPF


I have a WPF Window that contains a TextBox. I have implemented a Command that executes on Crtl-S that saves the contents of the window. My problem is that if the textbox is the active control, and I have newly edited text in the textbox, the latest changes in the textbox are not commited. I need to tab out of the textbox to get the changes.

In WinForms, I would typically call EndEdit on the form, and all pending changes would get commited. Another alternative is using onPropertyChange binding rather than onValidation, but I would rather not do this.

What is the WPF equivalent to EndEdit, or what is the pattern to use in this type of scenario?

Thanks,


Solution

  • To avoid the issue of needing to tab away, you could simply change the UpdateSourceTrigger property of your controls' binding. Try the following:

    <TextBox.Text>
        <Binding Path="MyProperty" UpdateSourceTrigger="PropertyChanged"/>
    </TextBox.Text>
    

    This tells WPF to update the backing object whenever the Text property is changed. This way, you don't need to worry about tabbing away. Hope this helps!

    EDIT:

    The accepted answer for the following SO question provides a way to automatically run validation rules for a page. You could modify it to call UpdateSource() on all BindingExpression objects instead.

    Link