PropertyGrid doesn't notice properties changed in code?

那年仲夏 提交于 2019-12-01 03:29:52

To answer your question on why the PropertyGrid doesn't change, the MSDN documentation for the PropertyGrid say this:

The information displayed in the grid is a snapshot of the properties at the time the object is assigned. If a property value of the object specified by the SelectedObject is changed in code at run time, the new value is not displayed until an action is taken in the grid that causes the grid to refresh.

So, it seems that the PropertyGrid is not a control that is auto-updatable. I think the clue to this is that the PropertyGrid uses the SelectedObject method instead of a DataSource method, and the latter would imply it probably listens to INotifyPropertyChanged.

You're left with what LarsTech has suggested and manually refreshing the grid.

Just try refreshing it:

private void button1_Click(object sender, EventArgs e)
{
  Colours colours = this.propertyGrid1.SelectedObject as Colours;
  colours.Reset();
  this.propertyGrid1.Refresh();
}

Assuming you will have more properties, you can use your PropertyChanged event. I would modify your Colour class like this:

public class Colours : INotifyPropertyChanged {
  public event PropertyChangedEventHandler PropertyChanged;

  private Color _ColourP1;

  public void Reset() {
    this.ColourP1 = Color.Red;
  }

  private void OnChanged(string propName) {
    if (PropertyChanged != null)
      PropertyChanged(this, new PropertyChangedEventArgs(propName));
  }

  public Color ColourP1 {
    get { return _ColourP1; }
    set {
      _ColourP1 = value;
      OnChanged("ColourP1");
    }
  }
}

Then your form would look like this:

public Form1() {
  InitializeComponent();

  Colours colours = new Colours();
  colours.PropertyChanged += colours_PropertyChanged;
  this.propertyGrid1.SelectedObject = colours;
}

private void colours_PropertyChanged(object sender, PropertyChangedEventArgs e) {
  this.propertyGrid1.Refresh();
}

private void button1_Click(object sender, EventArgs e) {
  ((Colours)this.propertyGrid1.SelectedObject).Reset();
}

Happened across this Question in trying to remember what I used to use and thought it might be useful to others.

You can use the [RefreshProperties] Attribute to trigger updates to the Property Grid.

eg:

    [RefreshProperties(RefreshProperties.All)]
    public int MyProperty{ get; set; }
Mudasir Khan Awan

Use DotNetBar AdvPropertyGrid control. You don't need any iNotify call to update it.
It automatically update grid whenever any object property change.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!