This is my data binding from a string (History.current_commad) to a text box (tbCommand):
history = new History();
Binding bind = new Binding("Command");
bind.Source = history;
bind.Mode = BindingMode.TwoWay;
bind.Path = new PropertyPath("current_command");
bind.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
// myDatetext is a TextBlock object that is the binding target object
tbCommand.SetBinding(TextBox.TextProperty, bind);
history.current_command = "test";
history.current_command is changing but the text box is not being update. What is wrong?
Thanks
The reason you don’t see the change reflected in the
TextBlockis becausecurrent_commandis just a field, so theBindingdoesn’t know when it’s been udpated.The easiest way to fix that is to have your
Historyclass implementINotifyPropertyChanged, convertcurrent_commandto a property, and then raise thePropertyChangedevent in the setter of your property:Now, when you assign a value to the
current_command, the event will fire, and theBindingwill know to update its target as well.If you find yourself with a lot of classes where you’d like to bind to their properties, you should consider moving the event and the helper method into a base class, so that you don’t write the same code repeatedly.