Igor
Igor

Reputation: 27250

Data binding in WPF on button click

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?

Upvotes: 1

Views: 4960

Answers (2)

PungE3
PungE3

Reputation: 11

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.

Upvotes: 1

Ivan Danilov
Ivan Danilov

Reputation: 14777

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.

Upvotes: 3

Related Questions