开发者

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}开发者_如何学C" />

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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜