WPF文本框只有在按下回车键时才更新绑定

9

所有的。我有一个名为"NumericTextBox"的用户控件,只允许输入数字。我需要展示另一种专门的行为,也就是,当我聚焦文本框并按下回车键时,我需要它能够绑定到一个VM值OneWayToSource,并且只有在这种情况下才更新VM值。我已经有了一个EnterPressed事件,在按下该键时触发,但我很难找到一种方法来导致该操作更新绑定...

3个回答

11

在您的绑定表达式中,将UpdateSourceTrigger设置为Explicit。

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

然后,在处理EnterPressed事件时,调用绑定表达式的UpdateSource方法,这将把文本框中的值推送到实际绑定的属性。

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

9

这里是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);
    }

这是一个不错的开端,但有一个错误。您的附加属性无法使用样式设置。要修复此问题,您应该在FrameworkPropertyMetadata构造函数中传递回调函数,并在其中订阅事件,而不是在SetUpdateSourceOnKey函数中添加事件处理程序。 - Soonts

3

如果您正在使用MVVM,您可以结合decastelijau的方法和自定义附加属性来实现在键盘预览事件(PreviewKeyUp)中调用TextBox的UpdateSource。

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);
}

然后你可以执行:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接