In a WPF application, I am creating a setting window to customize keyboard shortcuts.
In the textboxes, I handle the KeyDown event and convert the Key event to a human readable form (and also the form in which I want to have my data).
The text box is declared like this
<TextBox Text="{Binding ShortCutText, Mode=TwoWay}"/>
and in the event handler, I tried using both
(sender as TextBox).Text = "...";
and
(sender as TextBox).Clear();
(sender as TextBox).AppendText("...");
In both of these cases, the binding back to the viewmodel does not work, the viewmodel still contains the old data and does not get updated. Binding in the other direction (from viewmodel to the textbox) works fine.
Is there a way I can edit the TextBox.Text from code without using the binding? Or is there an error somewhere else in my process?
The event handler is called whenever the contents of the TextBox control are changed, either by a user or programmatically. This event fires when the TextBox control is created and initially populated with text.
Binding direction Updates the target property or the property whenever either the target property or the source property changes. BindingMode.OneWay. Updates the target property only when the source property changes.
This is a property on a binding that controls the data flow from a target to a source and used for two-way databinding. The default mode is when the focus changes but there are many other options available, that we will see in this article.
var box = sender as TextBox;
// Change your box text..
box.GetBindingExpression(TextBox.TextProperty).UpdateSource();
This should force your binding to update.
Don't change the Text property - change what you are binding to.
If your binding is destroyed by setting a new value (which is strange, for a two way binding the binding should stay intact), then use ((TextBox)sender).SetCurrentValue(TextBox.TextProperty, newValue) to leave the binding intact.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With