C# 如何根据属性网格中另一个属性的值公开一个属性?
我的课程具有多个属性。有时,可以在属性网格中编辑属性 (A)。但有时属性 A 可能无法编辑。这取决于另一个属性的值。
我该怎么做?
编辑: 抱歉,我忘记提及我希望在设计时做到这一点。
I have class with multiple properties. Sometimes a property (A) may be edited in a propertygrid. But sometimes property A may not be edited. This depends on a value of another property.
How can I do this?
EDIT:
I am sorry, I forget to mention that I want this in design-time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我过去通过 此堆栈解决方案。它使用自定义属性,并有条件地忽略在设计时与运行时进行更改的尝试,但我确信可以通过应用您自己的“标准”来更改 SETter 中的更改以允许更改...
I've offered a similar solution in the past via this stack solution. It makes use of a custom property, and conditionally ignores an attempt to change at design-time vs run-time, but I'm sure could be altered in the SETter by applying your own "criteria" to allow it being changed...
运行时属性模型是一个高级主题。对于PropertyGrid,最简单的方法是编写一个继承自ExpandableObjectConverter 的TypeConverter。重写 GetProperties,并将有问题的属性替换为自定义属性。
从头开始编写 PropertyDescriptor 是一件苦差事;但在这种情况下,您主要只需将所有方法链接(“装饰器”)到原始(反射)描述符。只需重写 IsReadOnly 即可返回您想要的布尔值。
绝不是微不足道的,而是可以实现的。
Runtime property models are an advanced topic. For PropertyGrid the easiest route would be to write a TypeConverter, inheriting from ExpandableObjectConverter. Override GetProperties, and swap the property in question for a custom one.
Writing a PropertyDescriptor from scratch is a chore; but in this case you mainly just need to chain ("decorator") all the methods to the original (reflective) descriptor. And just override IsReadOnly to return the bool you want.
By no means trivial, but achievable.
这个答案假设您正在谈论 WinForms。如果您想根据另一个属性更改一个属性的只读状态,则需要让您的对象 实现 ICustomTypeDescriptor。这不是一件简单的事情,但是它将为您的类在属性网格中的显示方式提供很大的灵活性。
This answer assumes you are talking about WinForms. If you would like to change one property's readonly state based on another, you will need to have your object implement ICustomTypeDescriptor. This isn't a simple thing to do, but it will give you lots of flexibility about how your class is displayed in the propertygrid.