0

I have implemented the INotifyPropertyChanged interface like this,

private int total; public event PropertyChangedEventHandler PropertyChanged; public void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public int Total { get { return this.Total; } set { if (this.total == value) return; this.total = value; this.NotifyPropertyChanged("TotalCost"); } } 

I have to bind the value of public int TotalCost to a textbox. The TotalCost would change whenever the value in some other textbox changes. I have done binding dynamically, Binding

bind = new Binding(); bind.Source = this.DataContext; TotalText.SetBinding(TextBox.TextProperty, bind); 

and setting the DataContext of this class as TotalCost. Where am i wrong? Thanks

3 Answers 3

4

I think that the reason the NotifyPropertyChanged is not fired is because of the property name mismatch. The name of the public property must be the same as the string which you pass to the NotifyPropertyChanged method. Therefore, instead of calling:

this.NotifyPropertyChanged("TotalCost"); 

you shoud be calling:

this.NotifyPropertyChanged("Total"); 

This should sove the problem.

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

Comments

2

Shouldn't your getter look like this?

get { return total; }

maybe it is getting set, but the getter isn't returning it...

2 Comments

Hi, Thanks for the reply. I have done the changes metioned. But the PropertyChanged is still showing null. What am I missing?
+1 The original code would cause stack overflow methinks. Looks like the OP fixed that bit already though.
0
private int _total=0; public int Total { get { return this._total; } set { if (this._total == value) return; this._total = value; this.NotifyPropertyChanged("Total"); } } ... bind = new Binding("DataContext.Total"); bind.Source = this; bind.Mode = BindingMode.TwoWay; TotalText.SetBinding(TextBox.TextProperty, bind); ... this.DataContext=this; 

3 Comments

Thanks for the reply but still the TotalText is not getting updated with the changed 'Total' value :(
I see that the NotifyPropertyChanged event is not invoked. what could be the reason?
Use: {return this.total;} in the getter, and make sure you set the DataContext with: this.DataContext=this; -- it is not set by default.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.