自动展开PropertyGrid中的某些属性

问题描述

我想通过在使用我的Settingsstructure类的实例加载的PropertyGrid中自动使用该类的属性来扩展某些节点。 另外,如果用户再次在PropertyGrid上加载该实例,我将尝试让实例“记住”是否扩展了每个属性

我做了一个真正有效的黑客工具,该工具大多数都可以使用。如果complex属性是PropertyGrid中显示的第一个属性,则它并不总是起作用。

有没有建议使用属性/类型转换器/相似的更好方法

这就是我所拥有的:

enter image description here

定义一个自定义属性,以表示它标记属性将开始扩展。

nifty['p'] = nifty['Pivot'].shift(-1)

从ExpandableObjectConverter派生您自己的类。

[AttributeUsage(AttributeTargets.Property)]
public class StartExpanded : Attribute {}

现在将它们应用于类中的属性显示在PropertyGrid中。 ASettingsNode只是一个抽象类,我用它来标记应加载到左侧TreeView中的属性

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);
    }
}

NameAgePair是我的课程。

[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
}

除了是HACK之外,如果网格中的第一项是我要扩展和记住的复杂属性之一,则无法使用。对于第一个属性,ConvertTo方法被无序调用,并且“记住”部分失败。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)