条件"可浏览"属性

Ido*_*dov 18 c# conditional properties browsable


有没有办法使"可浏览"属性成为条件,因此应用它的属性有时会出现在属性页面中,有时不会出现?
谢谢 :)

neo*_*kon 11

我不确定这适用于您的情况,但您可以通过调用下面的函数在运行时调整"可浏览"装饰.

/// <summary>
/// Set the Browsable property.
/// NOTE: Be sure to decorate the property with [Browsable(true)]
/// </summary>
/// <param name="PropertyName">Name of the variable</param>
/// <param name="bIsBrowsable">Browsable Value</param>
private void setBrowsableProperty(string strPropertyName, bool bIsBrowsable)
{
    // Get the Descriptor's Properties
    PropertyDescriptor theDescriptor = TypeDescriptor.GetProperties(this.GetType())[strPropertyName];

    // Get the Descriptor's "Browsable" Attribute
    BrowsableAttribute theDescriptorBrowsableAttribute = (BrowsableAttribute)theDescriptor.Attributes[typeof(BrowsableAttribute)];
    FieldInfo isBrowsable = theDescriptorBrowsableAttribute.GetType().GetField("Browsable", BindingFlags.IgnoreCase | BindingFlags.NonPublic | BindingFlags.Instance);

    // Set the Descriptor's "Browsable" Attribute
    isBrowsable.SetValue(theDescriptorBrowsableAttribute, bIsBrowsable);
}
Run Code Online (Sandbox Code Playgroud)


HAB*_*JAN 8

没有简单的方法.

您可以通过实现ICustomTypeDescriptor来解决这个问题.这是一篇关于实现ICustomTypeDescriptor的好文章.

或者,您可以将自己的ControlDesigner与类关联,并覆盖PreFilterProperties方法以添加或删除在属性网格中查看的属性.

从属性网格中删除某些属性.

  • 实现ICustomTypeDescriptor.got的链接指向https://msdn.microsoft.com/magazine/msdn-magazine-issues我认为他们已经删除了原始页面 (2认同)

Mar*_*ell 6

您可以通过提供自定义类型模型来完成此操作; 在最简单的级别,您可以TypeDescriptor为您的类型提供自定义ExpandableObjectConverter,并且只需在奇思妙想中包含/排除给定属性 - 但这仅适用于PropertyGrid- 由属性页面使用.更复杂的方法是使用ICustomTypeDescriptor/ TypeDescriptionProvider- 这可以在诸如此类的内容中工作DataGridView