Kam*_*eko 9 wpf binding textbox
所有.我有一个usercontrol"NumericTextBox",只允许数字输入.我需要展示另一种专门的行为,也就是说,我需要它能够将它绑定到VM值OneWayToSource,并且只有当我在聚焦文本框时按Enter键时才更新VM值.我已经有一个EnterPressed事件,当我按下键时会触发,我只是很难找到一种方法来使该动作更新绑定...
dec*_*jau 11
在绑定表达式中,将UpdateSourceTrigger设置为Explicit.
Text="{Binding ..., UpdateSourceTrigger=Explicit}"
Run Code Online (Sandbox Code Playgroud)
然后,在处理EnterPressed事件时,在绑定表达式上调用UpdateSource,这会将值从文本框推送到实际绑定属性.
BindingExpression exp = textBox.GetBindingExpression(TextBox.TextProperty);
exp.UpdateSource();
Run Code Online (Sandbox Code Playgroud)
以下是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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8974 次 |
| 最近记录: |