Hi, all. I have a usercontrol "NumericTextBox" that only allows numeric entries. I need to exhibit another specialized behaviour, that is, I need it to be able to bind it to a VM value OneWayToSource and only have the VM value update when I press enter while focusing the textbox. I already have the an EnterPressed event that fires when I press the key, I'm just having a hard time figuring out a way to cause that action to update the binding...
+4
A:
In your binding expression, set the UpdateSourceTrigger to Explicit.
Text="{Binding ..., UpdateSourceTrigger=Explicit}"
Then, when handling the EnterPressed event, call UpdateSource on the binding expression, this will push the value from the textbox to the actual bound property.
BindingExpression exp = textBox.GetBindingExpression(TextBox.TextProperty);
exp.UpdateSource();
decasteljau
2009-09-17 14:12:45
+2
A:
If you are using MVVM you can use a combination of decastelijau's approach along with a custom attached property that calls UpdateSource 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 can do:
<TextBox myprops:UpdaterProps.UpdateSourceOnKey="Enter" ... />
Anderson Imes
2009-09-17 14:36:44