Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change TextBox.Text without losing the binding in WPF?

Tags:

c#

mvvm

wpf

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?

like image 993
Tomas Grosup Avatar asked Sep 05 '12 11:09

Tomas Grosup


People also ask

Which event is generated when TextBox text is changed?

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.

What is one way binding in WPF?

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.

What is Updateourcetrigger WPF?

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.


3 Answers

var box = sender as TextBox;
// Change your box text..

box.GetBindingExpression(TextBox.TextProperty).UpdateSource();

This should force your binding to update.

like image 68
KyorCode Avatar answered Oct 06 '22 21:10

KyorCode


Don't change the Text property - change what you are binding to.

like image 27
Kieren Johnstone Avatar answered Oct 06 '22 21:10

Kieren Johnstone


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.

like image 2
Rob van Daal Avatar answered Oct 06 '22 21:10

Rob van Daal