首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >c#属性设置器不适用于我的组件

c#属性设置器不适用于我的组件
EN

Stack Overflow用户
提问于 2018-05-19 06:01:20
回答 1查看 1.2K关注 0票数 1

我在为自己设计一个组件。组件的一个属性是"Status“,它的类型为"StatusClass”。

MyCode是:

代码语言:javascript
复制
private StatusClass _mStatus=new StatusClass();
public StatusClass Status
{
    get { return this._mStatus; }
    set
    {
        this._mStatus = value;
        this.Refresh();
    }
}

问题是,当StatusClass的一个属性发生变化时,setter/"Refresh“方法不会调用。例如:

代码语言:javascript
复制
myComponent.Status.proprety1 = 3;  // the "Refresh method not call

但是:

代码语言:javascript
复制
myComponent.Status = new StatusClass(); // the "Refresh method called

如何正确定义Status属性,以便通过更改其值来调用setter函数。

谢谢,

EN

回答 1

Stack Overflow用户

发布于 2018-05-19 06:18:30

Status的实例被更新为新对象时,就会调用refresh方法,因为您已经在setter this.Refresh();中定义了它。

代码语言:javascript
复制
myComponent.Status = new StatusClass(); // the "Refresh method called

它不会被这一行调用

代码语言:javascript
复制
myComponent.Status.proprety1 = 3;  // the "Refresh method not call

在这里,您正在更新的属性 of Status,而不是对象本身。

为了实现这一点,即使在更改Status类的属性时,也应该在调用方类中接收通知,然后实现INotifyPropertyChanged接口,该接口可以帮助通知客户端属性值已经更改。你可以读到它,这里

代码语言:javascript
复制
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();
            }
        }
    }
}

现在,在调用程序类中,您可以将对象定义为

代码语言:javascript
复制
public class DemoClass
{
     private StatusClass _mStatus = new StatusClass();

     public DemoClass()
     {
          _mStatus.PropertyChanged = (sender, args) => { this.Refresh(); }
     }
}

因此,当现在调用myComponent.Status.Proprety1 = 3;时,刷新将被调用,因为它订阅了更改了StatusClass的属性。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50422293

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档