1

I am trying to implement data binding, and to have TextBox's text to be update once I click on some button.

XAML:

<TextBox  Text="{Binding Path=Output}" />

Code:

    public MainWindow()
    {
        InitializeComponent();
        DataContext = Search;
        Search.Output = "111";
    }

    public SearchClass Search = new SearchClass();


    private void button1_Click(object sender, RoutedEventArgs e)
    {
        Search.Output = "222";
    }

    public class SearchClass
    {
        string _output;

        public string Output
        {
            get { return _output; }
            set { _output = value; }
        }
    }

When I execute the program, I see "111", so the binding from MainWindow() works, but if I click a button - the text in the TextBox is not updated (but in the debugger I see that button1_Click is executed and Search.Output is now equal to "222"). What am I doing wrong?

2 Answers 2

3

You should implement INotifyPropertyChanged in your SearchClass and then in setter raise the event:

public event PropertyChangedEventHandler PropertyChanged = delegate { };
public string Output
{
    get { return _output; }
    set 
    { 
        _output = value; 
        PropertyChanged(this, new PropertyChangedEventArgs("Output")); 
    }
}

If I understood right, SearchClass is the DataContext for your TextBlock. In this case implementing as above would help.

When WPF see some class as the source of Binding - it tries to cast it to INotifyPropertyChanged and subscribe to PropertyChanged event. And when event is raised - WPF updates the binding associated with sender (first argument of PropertyChanged). It is the main mechanism that makes binding work so smoothly.

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

Comments

1

You have to implement the INotifyPropertyChanged interface on your SearchClass class. This is how binder values are notified their source values have changed. It displays the "111" value because it hasn't been laid out yet (more or less), but will won't update after that until you implement that interface.

Comments

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.