Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
仅在按下enter键时更新绑定的WPF文本框_Wpf_Binding_Textbox - Fatal编程技术网

仅在按下enter键时更新绑定的WPF文本框

仅在按下enter键时更新绑定的WPF文本框,wpf,binding,textbox,Wpf,Binding,Textbox,全部。我有一个用户控件“NumericTextBox”,它只允许数字输入。我需要展示另一种特殊的行为,也就是说,我需要它能够将它绑定到一个VM值OneWayToSource,并且只有当我在聚焦文本框的同时按enter键时,才会更新VM值。我已经有一个EnterPressed事件,当我按下该键时会触发,我只是很难找到一种方法使该操作更新绑定…在绑定表达式中,将UpdateSourceTrigger设置为Explicit Text="{Binding ..., UpdateSourceTrigger

全部。我有一个用户控件“NumericTextBox”,它只允许数字输入。我需要展示另一种特殊的行为,也就是说,我需要它能够将它绑定到一个VM值OneWayToSource,并且只有当我在聚焦文本框的同时按enter键时,才会更新VM值。我已经有一个EnterPressed事件,当我按下该键时会触发,我只是很难找到一种方法使该操作更新绑定…

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

Text="{Binding ..., UpdateSourceTrigger=Explicit}"
然后,在处理EnterPressed事件时,对绑定表达式调用UpdateSource,这将把文本框中的值推送到实际的绑定属性

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

如果您使用的是MVVM,那么您可以结合使用decastelijau的方法以及一个自定义附加属性,该属性在PreviewKeyUp时在文本框上调用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" ... />

以下是安德森·艾姆斯(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);
    }