【问题标题】:How to force NotifyPropertyChanged on a collection object [duplicate]如何在集合对象上强制 NotifyPropertyChanged [重复]
【发布时间】:2018-07-08 13:50:34
【问题描述】:

我有一个类,我通常如下定义一个属性:

public class MeasurementPoint : ModelBase
{
    private double _value;
    public double Value
    {
        get { return _value; }
        set
        {
            _value = value;
            NotifyPropertyChanged();
        }
    }
}

接下来我创建了一个包含许多“MeasurementPoint”对象的集合。我想在每个满足特定值逻辑的对象上提高 notifyPropertyChanged。

目前此方法有效,并且引发了 propertyChanged。但是,肯定有更有效的方法来做到这一点吗?

private void RefreshDataGridTolerance()
{
    foreach (var measurementPoint in DataSet)
    {
        //TODO: Change this into a real way to raiseproperty changed without actually changing the value
        var temp = measurementPoint.Value;
        measurementPoint.Value = temp;

        // something like this doesnt work?
        // RaisePropertyChanged(nameof(measurementPoint.Value));
    }
}

集合定义如下:ObservableCollection<MeasurementPoint> DataSet

【问题讨论】:

    标签: c# inotifypropertychanged


    【解决方案1】:

    您可以在模型类中实现一个公共方法,该方法将为每个定义的属性引发属性更改事件。最便宜的方法可能是这样的:

    public class MeasurementPoint : ModelBase
    {
      //...
      public void RefreshAllProperties()
      {
        foreach(var prop in this.GetType().GetProperties())
          this.OnPropertyChanged(prop.Name);
      }
    }
    

    您可以像这样刷新一个数据元素的绑定。

    var element = DataSet.First();
    element.RefreshAllProperties();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-30
      • 1970-01-01
      相关资源
      最近更新 更多