WPF data binding does not work
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 TextBlock
is because current_command
is just a field, so the Binding
doesn't know when it's been udpated.
The easiest way to fix that is to have your History
class implement INotifyPropertyChanged
, convert current_command
to a property, and then raise the PropertyChanged
event in the setter of your property:
public class History : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
private string _current_command;
public string current_command
{
get
{
return _current_command;
}
set
{
if (_current_command == null || !_current_command.Equals(value))
{
// Change the value and notify that the property has changed
_current_command = value;
NotifyPropertyChanged("current_command");
}
}
}
}
Now, when you assign a value to the current_command
, the event will fire, and the Binding
will 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.
精彩评论