【发布时间】:2020-10-23 13:55:52
【问题描述】:
我想通过使用该类的属性上的属性来自动扩展加载有我的 SettingsStructure 类实例的 PropertyGrid 中的一些节点。 此外,如果用户在 PropertyGrid 上再次加载该实例,我试图让实例“记住”每个属性是否被扩展。
我做了一个真正有效的 HACK。如果复杂属性是 PropertyGrid 中显示的第一个属性,它并不总是有效。
对使用属性/类型转换器/类似的更好方法有什么建议吗?
这是我所拥有的:
定义一个自定义的Attribute,表示它所标记的属性是开始展开的。
[AttributeUsage(AttributeTargets.Property)]
public class StartExpanded : Attribute {}
从 ExpandableObjectConverter 派生您自己的类。
public class MyExpandableObjectConverter : ExpandableObjectConverter
{
private bool _IsFirstUse = true;
private bool _JustShownInPropertyGrid = false;
private bool _WasLastExpanded = false;
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
//This method is called every time the propertygrid shows this property
if (_IsFirstUse)
{
_IsFirstUse = false;
_WasLastExpanded = context.PropertyDescriptor.Attributes[typeof(StartExpanded)] != null;
}
_JustShownInPropertyGrid = true;
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
//This method is called after CanConvertFrom and also on other operations and when leaving showing this property
if (_JustShownInPropertyGrid)
{
_JustShownInPropertyGrid = false;
if (_WasLastExpanded)
{
var GI = (GridItem)context;
GI.Expanded = true;
}
}
else
{
var GI = (GridItem)context;
_WasLastExpanded = GI.Expanded;
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
现在将它们应用到要在 PropertyGrid 中显示的类中的属性。 ASettingsNode 只是一个抽象类,我用它来标记应该加载到左侧 TreeView 中的属性。
[Serializable]
public class SettingsStructure : ASettingsNode
{
public string FamilyName { get; set; } = "Rogers";
[StartExpanded]
[TypeConverter(typeof(MyExpandableObjectConverter))]
public NameAgePair Dad { get; set; } = new NameAgePair() { Name = "Buck", Age = 51};
[StartExpanded]
[TypeConverter(typeof(MyExpandableObjectConverter))]
public NameAgePair Mom { get; set; } = new NameAgePair() { Name = "Wilma", Age = 50};
public string NameOfSomebody { get; set; } = "Phoebe";
//... and other nodes that are derived from ASettingsNode to show up in the TreeView
}
这里 NameAgePair 是我的班级。
public class NameAgePair
{
public string Name { get; set; } = "";
public int Age { get; set; } = 0;
public override string ToString()
{
return $"{Name} ({Age})";
}
}
除了作为 HACK 之外,如果网格中的第一项是我想要扩展和记住的复杂属性之一,则它不起作用。对于第一个属性,ConvertTo 方法被乱序调用,“remember”部分失败。
【问题讨论】:
-
您好,我也有同样的问题……请问您找到解决方案了吗……
-
还有`propertyGrid.PropertyValueChanged += (ss, ee) => { if (ee.ChangedItem.Expandable) ee.ChangedItem.Expanded = true; };` 在我身边不起作用....
-
@deveton 我辞职以确保第一个项目不是复杂项目。
-
好吧,你试试什么解决方案...
标签: c# attributes propertygrid