[ACCEPTED]-WPF textbox that only updates binding when enter is pressed-textbox

Accepted answer
Score: 11

In your binding expression, set the UpdateSourceTrigger 4 to Explicit.

Text="{Binding ..., UpdateSourceTrigger=Explicit}"

Then, when handling the EnterPressed 3 event, call UpdateSource on the binding 2 expression, this will push the value from 1 the textbox to the actual bound property.

BindingExpression exp = textBox.GetBindingExpression(TextBox.TextProperty);
exp.UpdateSource();
Score: 9

Here is a complete version of the idea provided 1 by Anderson Imes:

public static readonly DependencyProperty UpdateSourceOnKeyProperty = 
    DependencyProperty.RegisterAttached("UpdateSourceOnKey", 
    typeof(Key), typeof(TextBox), new FrameworkPropertyMetadata(Key.None));

    public static void SetUpdateSourceOnKey(UIElement element, Key value) {
        element.PreviewKeyUp += TextBoxKeyUp;
        element.SetValue(UpdateSourceOnKeyProperty, value);
    }

    static void TextBoxKeyUp(object sender, KeyEventArgs e) {

        var textBox = sender as TextBox;
        if (textBox == null) return;

        var propertyValue = (Key)textBox.GetValue(UpdateSourceOnKeyProperty);
        if (e.Key != propertyValue) return;

        var bindingExpression = textBox.GetBindingExpression(TextBox.TextProperty);
        if (bindingExpression != null) bindingExpression.UpdateSource();
    }

    public static Key GetUpdateSourceOnKey(UIElement element) {
        return (Key)element.GetValue(UpdateSourceOnKeyProperty);
    }
Score: 3

If you are using MVVM you can use a combination 4 of decastelijau's approach along with a 3 custom attached property that calls UpdateSource 2 on the textbox when PreviewKeyUp.

public static readonly DependencyProperty UpdateSourceOnKey = DependencyProperty.RegisterAttached(
  "UpdateSourceOnKey",
  typeof(Key),
  typeof(TextBox),
  new FrameworkPropertyMetadata(false)
);
public static void SetUpdateSourceOnKey(UIElement element, Key value)
{

  //TODO: wire up specified key down event handler here
  element.SetValue(UpdateSourceOnKey, value);

}
public static Boolean GetUpdateSourceOnKey(UIElement element)
{
  return (Key)element.GetValue(UpdateSourceOnKey);
}

Then you 1 can do:

<TextBox myprops:UpdaterProps.UpdateSourceOnKey="Enter" ... />

More Related questions