views:

108

answers:

3

Hi, 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

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

Hi, 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.

Przemek
+2  A: 

Shouldn't your getter look like this?

get { return total; }

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

Chris Koenig
Hi, Thanks for the reply. I have done the changes metioned. But the PropertyChanged is still showing null. What am I missing?
Ramya
+1 The original code would cause stack overflow methinks. Looks like the OP fixed that bit already though.
Igor Zevaka