gpt4 book ai didi

c# - PropertyGrid 没有注意到代码中的属性更改?

转载 作者:可可西里 更新时间:2023-11-01 08:35:16 33 4
gpt4 key购买 nike

我有一个 Winform 应用程序,它使用颜色来突出显示某些内容。我想让用户更改“他们的”颜色。作为练习,我想我会创建一个类的实例,其中包含颜色属性,并将其分配给属性网格(以获得一个不错的编辑器)

这似乎工作正常,但我想我想让用户重置颜色(在他们摆弄并将它们设置为 20 种米色阴影之后)。因此,我在我的表单中添加了一个“重置”按钮,它将我的对象的颜色属性设置回默认值。

但是,似乎虽然它设置了我的对象的属性,但属性网格并没有改变。如果在重置后,我执行属性网格“刷新”,它具有重置颜色。

我假设属性网格不知道底层对象已更改?

在这种情况下是否缺少某些东西,或者我应该接受它并在重置我的对象时调用 Refresh 方法?

谢谢

(非常相似的问题 here )

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

this.propertyGrid1.SelectedObject = new Colours();
}

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

public partial class Colours : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

public Color ColourP1 { get; set; }

public void Reset()
{
this.ColourP1 = Color.Red;
var handler = this.PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs("ColourP1"));
}
}

根据我对“没有订阅 INotifyPropertyChanged.PropertyChanged” 的评论,将 PropertyGrid 控件子类化有什么缺点?

public partial class MyPropertyGrid : System.Windows.Forms.PropertyGrid
{
private INotifyPropertyChanged _selectedObject;

protected override void OnSelectedObjectsChanged(EventArgs e)
{
base.OnSelectedObjectsChanged(e);

if (_selectedObject != null) _selectedObject.PropertyChanged -= selectedObject_PropertyChanged;
_selectedObject = this.SelectedObject as INotifyPropertyChanged;
if (_selectedObject != null) _selectedObject.PropertyChanged += selectedObject_PropertyChanged;
}

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

最佳答案

要回答有关 PropertyGrid 为何不更改的问题,请参阅 PropertyGrid 的 MSDN 文档这么说:

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.

因此,PropertyGrid 似乎不是可自动更新的控件。我认为这方面的线索是 PropertyGrid 使用 SelectedObject 方法而不是 DataSource 方法,后者暗示它可能会监听 INotifyPropertyChanged。

剩下的就是 LarsTech 的建议和手动刷新网格。

关于c# - PropertyGrid 没有注意到代码中的属性更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10092162/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com