Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 226
Thies Avatar asked May 20 '09 14:05

Thies


2 Answers

Based on Pwninstein answer, I have now implemented an EndEdit in my common class for WPF Views / Windows that will look for bindings and force an update on them, code below;

Code below;

private void EndEdit(DependencyObject parent)
{
    LocalValueEnumerator localValues = parent.GetLocalValueEnumerator();
    while (localValues.MoveNext())
    {
        LocalValueEntry entry = localValues.Current;
        if (BindingOperations.IsDataBound(parent, entry.Property))
        {
            BindingExpression binding = BindingOperations.GetBindingExpression(parent, entry.Property);
            if (binding != null)
            {
                binding.UpdateSource();
            }
        }
    }            

    for(int i=0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(parent, i);
        this.EndEdit(child);
    }
}

protected void EndEdit()
{
    this.EndEdit(this);
}

In my Save command, I now just call the EndEdit method, and I don't have to worry about other programmers selection of binding method.

like image 129
Thies Avatar answered Sep 30 '22 00:09

Thies


You can force specific bindings to update using code like the following:

var bindingExpression = txtInput.GetBindingExpression(TextBox.TextProperty);
bindingExpression.UpdateSource();

Doing this more generally is difficult because there is no generic way to get all bindings, nor would you necessarily want them all to updated.

like image 42
David Nelson Avatar answered Sep 29 '22 22:09

David Nelson