我在为自己设计一个组件。组件的一个属性是"Status“,它的类型为"StatusClass”。
MyCode是:
private StatusClass _mStatus=new StatusClass();
public StatusClass Status
{
get { return this._mStatus; }
set
{
this._mStatus = value;
this.Refresh();
}
}问题是,当StatusClass的一个属性发生变化时,setter/"Refresh“方法不会调用。例如:
myComponent.Status.proprety1 = 3; // the "Refresh method not call但是:
myComponent.Status = new StatusClass(); // the "Refresh method called如何正确定义Status属性,以便通过更改其值来调用setter函数。
谢谢,
发布于 2018-05-19 06:18:30
当Status的实例被更新为新对象时,就会调用refresh方法,因为您已经在setter this.Refresh();中定义了它。
myComponent.Status = new StatusClass(); // the "Refresh method called它不会被这一行调用
myComponent.Status.proprety1 = 3; // the "Refresh method not call在这里,您正在更新的属性 of Status,而不是对象本身。
为了实现这一点,即使在更改Status类的属性时,也应该在调用方类中接收通知,然后实现INotifyPropertyChanged接口,该接口可以帮助通知客户端属性值已经更改。你可以读到它,这里。
public class StatusClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private int proprety1
public int Proprety1
{
get
{
return this.proprety1;
}
set
{
if (value != this.proprety1)
{
this.proprety1 = value;
NotifyPropertyChanged();
}
}
}
}现在,在调用程序类中,您可以将对象定义为
public class DemoClass
{
private StatusClass _mStatus = new StatusClass();
public DemoClass()
{
_mStatus.PropertyChanged = (sender, args) => { this.Refresh(); }
}
}因此,当现在调用myComponent.Status.Proprety1 = 3;时,刷新将被调用,因为它订阅了更改了StatusClass的属性。
https://stackoverflow.com/questions/50422293
复制相似问题