我编写以下代码将数据从后台对象绑定到WinForm UI。我使用INotifyPropertyChanged接口来通知UI属性更改。但我没有看到任何事件处理程序被明确地分配给事件PropertyChanged。我用.NET Reflector检查了我的程序集,但仍然没有找到相应的事件处理程序? PropertyChanged事件的事件处理程序在哪里?这是微软的又一个编译技巧吗?
这是后台对象的代码:
public class Calculation :INotifyPropertyChanged
{
private int _quantity, _price, _total;
public Calculation(int quantity, int price)
{
_quantity = quantity;
_price = price;
_total = price * price;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)// I DIDN'T assign an event handler to it, how could
// it NOT be null??
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
public int Quantity
{
get { return _quantity; }
set
{
_quantity = value;
//Raise the PropertyChanged event
NotifyPropertyChanged("Quantity");
}
}
public int Price
{
get { return _price; }
set
{
_price = value;
//Raise the PropertyChanged event
NotifyPropertyChanged("Price");
}
}
public int Total
{
get { return _quantity * _price; }
}
}
非常感谢!
答案 0 :(得分:1)
我不确定我是否理解这个问题,但是如果你正在使用数据绑定,它是绑定到你的类的绑定控件/表单 - 通过INotifyPropertyChanged
接口(如本例所示)或反映*Changed
模式(通过PropertyDescriptor
)。如果确实希望您可以截取事件的add
/ remove
部分并查看堆栈跟踪以查看添加/删除处理程序的人员:
private PropertyChangedEventHandler propertyChanged;
public event PropertyChangedEventHandler PropertyChanged {
add { propertyChanged += value; } // <<======== breakpoint here
remove { propertyChanged -= value; } // <<===== breakpoint here
}