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,
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With