PropertyGrid - 动态改变ReadOnlyAttribute
叹息,另一个 PropertyGrid 问题。我以为我可以解决这个问题,直到我遇到了一个我实际上无法避免的问题。
我有一个布尔属性,有时需要是只读的,有时需要根据从 TreeView 中选择的对象进行更改。
我的问题是如何动态更改属性的 ReadOnlyAttribute?显然,创建一个布尔变量然后尝试像 ReadOnlyAttribute(boolVar) 一样设置它是行不通的,现在我已经没有主意了。
我能想到的唯一解决方案是为该属性可写和只读的项目创建单独的、几乎相同的类,但这对我来说似乎有点不优雅。
帮助? :)
Sigh, another PropertyGrid question. I thought I could get around this until I ran into a problem where I couldn't actually avoid it.
I have a boolean property that sometimes needs to be read-only and sometimes needs to be changeable depending on the object selected from a TreeView.
My question is how can I change the ReadOnlyAttribute of a property dynamically? Obviously, creating a boolean variable and then trying to set it like ReadOnlyAttribute(boolVar) doesn't work and now I'm out of ideas.
The only solution I can think of is creating separate, near-identical classes for items where this property is writable and one for read-only, but this seems a bit unelegant to me.
Help? :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过实现 ICustomTypeDescriptor。
属性网格将调用 ICustomTypeDescriptor.GetProperties() 并且您返回派生自 PropertyDescriptors 的对象集合。在您的实现中,您可以覆盖 PropertyDescriptor.IsReadOnly 属性并实现您的逻辑。
首先,这是一项相当大的工作,但它使您可以动态返回属性名称和描述(有助于本地化)、动态将属性标记为只读、动态显示和隐藏属性,以及做很多事情其他有用的东西。
You can provide dynamic information about the properties of a class to a property grid by implementing ICustomTypeDescriptor.
The property grid will call ICustomTypeDescriptor.GetProperties() and you return a collection of objects derived from PropertyDescriptors. In your implementation you can override the PropertyDescriptor.IsReadOnly property and implement your logic.
This is quite a bit of work in the first place, but it gives you the possibility to dynamically return a property name and description (helpful for localization), dynamically mark properties as read-only, dynamiclly show and hide properties, and do a lot of other usefull things.
我要做的是创建一个具有受保护版本属性的基类,然后创建两个继承具有只读和非只读位的基类的类。
What I would do is create a base class with a protected version the property, then create two classes that inherit the base class that have the readonly and the non-readonly bits.
您可以尝试按照以下方式进行操作,以避免涉及多个类的类型转换:
You could try something along these lines to avoid the type conversion involved with multiple classes: