Ramya
Ramya

Reputation: 611

How to invoke INotifyPropertyChanged

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

Upvotes: 0

Views: 362

Answers (3)

Andy
Andy

Reputation: 3743

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;

Upvotes: 0

Chris Koenig
Chris Koenig

Reputation: 2748

Shouldn't your getter look like this?

get { return total; }

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

Upvotes: 2

Przemek
Przemek

Reputation: 825

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.

Upvotes: 4

Related Questions