Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force binding to update when Command is triggered

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.

like image 358
poke Avatar asked Jun 18 '12 15:06

poke


2 Answers

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();
    }
like image 173
Kai G Avatar answered Sep 28 '22 13:09

Kai G


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

like image 33
user3791372 Avatar answered Sep 28 '22 13:09

user3791372