全部。我有一個只允許數字輸入的用戶控件「NumericTextBox」。我需要展示另一種專門的行爲,也就是說,我需要它能夠將其綁定到VM值OneWayToSource,並且只有在按住Enter鍵的同時對焦文本框時纔會更新VM值。我已經有一個EnterPressed事件,當我按下按鍵時會觸發,我只是很難找出一種方法來引起該操作來更新綁定...WPF文本框僅在輸入時才更新綁定
9
A
回答
11
在綁定表達式中,將UpdateSourceTrigger明確。
Text="{Binding ..., UpdateSourceTrigger=Explicit}"
然後,處理EnterPressed事件時,調用UpdateSource上的結合表達,這將從文本框推值實際綁定屬性。
BindingExpression exp = textBox.GetBindingExpression(TextBox.TextProperty);
exp.UpdateSource();
3
如果您正在使用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" ... />
7
這裏是由安德森艾姆斯提供的想法的完整版本:
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);
}