is there a way to update a binding before or when a command is triggered? I have some text fields I can edit and save using a command, accessible via a keyboard shortcut. As the binding is usually only updated when the text field loses focus, the last change is not kept when pressing the key to save the data. Instead I have to tab out of the text field first to make it update and then save it.
Is there a way to force the update in an elegant way? I am using MVVM (but not any MVVM framework), so I’d like to keep UI specific things out of the command code. Also I don’t really want to change the binding to update on every change, it’s fine to have it update only when the focus is lost.
Rather than changing focus you could also just update the binding source if the current element is a TextBox
. You could do something similar for other controls but in my experience I've only had this problem with TextBox
.
// if the current focused element is textbox then updates the source.
var focusedElement = Keyboard.FocusedElement as FrameworkElement;
if (focusedElement is TextBox)
{
var expression = focusedElement.GetBindingExpression(TextBox.TextProperty);
if (expression != null) expression.UpdateSource();
}
On your TextBox
, you need to set the UpdateSourceTrigger
on your text binding which defines when the source will be updated with the textbox value. By default it's LostFocus
for the Text
property, which is exactly what's happening - it only updates the source when it loses focus. You should set the value of UpdateSourceTrigger
to PropertyChanged
and it will update each time the textbox value changes.
e.g.
<TextBox ... Text="{Binding Foo, UpdateSourceTrigger=PropertyChanged}"/>
Path is the default property when using the Binding command, so the above is equal to Path=Foo
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