c # свойство Setter не работает для моего компонента - PullRequest
0 голосов
/ 19 мая 2018

Я разрабатываю компонент для себя.Одним из свойств компонента является «Status», который имеет тип «StatusClass».

MyCode:

private StatusClass _mStatus=new StatusClass();
public StatusClass Status
{
    get { return this._mStatus; }
    set
    {
        this._mStatus = value;
        this.Refresh();
    }
}

проблема заключается в том, что метод setter / «Refresh» не вызывается, когдаизменяется одно свойство StatusClass.например:

myComponent.Status.proprety1 = 3;  // the "Refresh method not call

но:

myComponent.Status = new StatusClass(); // the "Refresh method called

как правильно определить свойство Status, чтобы при изменении его значения вызывалась функция установки.

Спасибо,

1 Ответ

0 голосов
/ 19 мая 2018

Метод refresh вызывается, когда экземпляр Status обновляется до нового объекта, как вы определили его в сеттере this.Refresh();.

myComponent.Status = new StatusClass(); // the "Refresh method called

И эта строка не будет вызываться

myComponent.Status.proprety1 = 3;  // the "Refresh method not call

, поскольку здесь вы обновляете свойство из Status вместо самого объекта.

Чтобы добиться этого даже при изменении свойств класса Status, уведомление должно быть получено в классе invoker, затем вы реализуете интерфейс 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();
            }
        }
    }
}

Теперь в классе invoker вы можете определить объект как

public class DemoClass
{
     private StatusClass _mStatus = new StatusClass();

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

Так что когда теперь вызывается myComponent.Status.Proprety1 = 3;,Обновление будет вызвано, так как оно подписано на свойство, измененное StatusClass.

...