且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使属性在 DataGridView 中可见但在 PropertyGrid 中不可见?

更新时间:2022-06-27 02:40:20

可以通过使用 PropertyGrid 的 BrowsableAttributes 属性来解决此问题.首先,创建一个像这样的新属性:

it is possible to solve this issue by using the BrowsableAttributes property of a PropertyGrid. First, create a new attribute like this:

public class PropertyGridBrowsableAttribute : Attribute
{
    private bool browsable;
    public PropertyGridBrowsableAttribute(bool browsable){
        this.browsable = browsable;
    }
}

然后将此属性添加到您希望在 PropertyGrid 中显示的所有属性:

Then add this attribute to all those properties which you want to be shown in your PropertyGrid:

[DisplayName("First Name"), Category("Names"), PropertyGridBrowsable(true)]
public string FirstName {
    get { return ... }
    set { ... }
}

然后像这样设置 BrowsableAttributes 属性:

Then set the BrowsableAttributes property like this:

myPropertyGrid.BrowsableAttributes = new AttributeCollection(
    new Attribute[] { new PropertyGridBrowsableAttribute(true) });

这只会显示属性网格中的属性属性,而 DataGridView 仍然可以访问所有属性,只需多做一点编码工作.

This will only show the attributed properties in your property grid and the DataGridView can still access all properties with only a little bit more coding effort.

我仍然会选择 Tergiver 并将这种行为称为错误,因为 Browsable 属性的文档明确说明它仅用于属性窗口.

I would still go with Tergiver and call this behaviour a bug, since the documentation of the Browsable attribute clearly states its use for property windows only.

(归功于 http://www.mycsharp.de/wbb2/上的用户maro"thread.php?postid=234565)