开发者

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


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.


Shouldn't your getter look like this?

get { return total; }

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


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;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜