0

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

2
  • What does the History class look like? Commented Aug 20, 2011 at 6:06
  • public class History { public string current_command; } Commented Aug 20, 2011 at 6:10

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi @dlev, can you have a look at this problem? stackoverflow.com/questions/7130143/… The reason I'm doing data binding in code is I could not get the xmlns thing right. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.