我想通过使用我的 SettingsStructure 类的实例来自动扩展 PropertyGrid 中的一些节点,方法是使用该类的属性。 此外,如果用户再次在 PropertyGrid 上加载该实例,我试图让实例“记住”每个属性是否已展开。
我做了一个真正有效的 HACK。如果复杂属性是 PropertyGrid 中显示的第一个属性,它并不总是有效。
关于使用属性/类型转换器/类似物的更好方法有什么建议吗?
这是我的:
定义一个自定义属性来表示它标记的属性将开始展开。
[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 是我的类(class)。
public class NameAgePair
{
public string Name { get; set; } = "";
public int Age { get; set; } = 0;
public override string ToString()
{
return $"{Name} ({Age})";
}
}
除了是一个 HACK,如果网格中的第一项是我想要扩展和记住的复杂属性之一,它就不起作用。对于第一个属性,ConvertTo 方法被乱序调用,“记住”部分失败。
最佳答案
在 MSPG 中设置初始扩展状态没有直接的解决方案。只有骇客。而且,如您所见,尝试在 TypeConverter 中执行此操作并不容易。此外,没有内置的方法来保存和恢复网格的各种状态。
作为从头开始制作的自定义 PropertyGrid 的开发人员,我尝试实现您的两个要求。而且它绝对只适用于几行代码。如果可以选择商业产品,you can have a look .
关于c# - 自动展开PropertyGrid中的一些属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64501360/