我有一个基类(节点)和一些继承的类型。
Class Node
{
Base_Attributes...
}
Class Derived : Node
{
Derived_Attributes...
}
这些类型在我添加到项目中的dll中。有一类,假设Item的属性之一是Node。我有一个Propertygrid,其中显示了我的属性,如下所示:
Class Item
{
Point location;
String name;
Node quiddity;
bool[] IsBrowsable;
public Point Location{set;get;}
public String Name{set;get;}
public String NodeAttrib{set;get;}
[Browsable(IsBrowsable[thisindex])]
public String DerivedTypeAttribe{set;get;}
[Browsable(IsBrowsable[otheroneindex])]
public String DerivedTypeAttribe{set;get;}
Item(string type)
{
switch(type)
{
case"some":
Node = new derived_some();
IsBrowsable[thisindex] = true;
break;
}
}
}
在主要形式中:
propertygrid.selectedobject = item;
这里的问题是为派生类型指定了一些属性,我需要在propetygrid中显示它们,但是直到运行时才知道节点的类型。我尝试使用布尔数组设置Browsabl()属性,但事实证明Browsable Parameter需要为常数。有什么主意我该如何通过?
最佳答案
这是通过TypeDescriptor
过滤的示例;您当然可以更改“我如何知道要显示的属性”代码-这纯粹是说明性的:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
PropertyGrid grid;
using (var form = new Form
{
Controls = { (grid = new PropertyGrid { Dock = DockStyle.Fill}) }
})
{
grid.SelectedObject = new Magic {ShowY = false};
Application.Run(form);
}
}
}
[TypeConverter(typeof(MagicTypeConverter))]
public class Magic
{
public Magic()
{
ShowX = ShowY = ShowZ = true;
}
public int A { get; set; }
public bool B { get; set; }
public string C { get; set; }
public int X { get; set; }
public bool Y { get; set; }
public string Z { get; set; }
[Browsable(false)]
public bool ShowX { get; set; }
[Browsable(false)]
public bool ShowY { get; set; }
[Browsable(false)]
public bool ShowZ { get; set; }
private class MagicTypeConverter : ExpandableObjectConverter
{
public override PropertyDescriptorCollection GetProperties(
ITypeDescriptorContext context, object value,
Attribute[] attributes)
{
var original = base.GetProperties(context, value, attributes);
var list = new List<PropertyDescriptor>(original.Count);
var magic = (Magic)value;
foreach (PropertyDescriptor prop in original)
{
bool showProp = true;
switch (prop.Name)
{
case "X": showProp = magic.ShowX; break;
case "Y": showProp = magic.ShowY; break;
case "Z": showProp = magic.ShowZ; break;
}
if (showProp) list.Add(prop);
}
return new PropertyDescriptorCollection(list.ToArray());
}
}
}
关于c# - 条件属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11176722/