UserControl 自定义属性变灰

Mar*_*rco 1 c# properties custom-controls

我很确定这是一个愚蠢的问题,但我所有的尝试都失败了。
我有一个自定义控件,我希望在其中有一个复杂的属性来公开许多属性。我想这样做是因为我在可视化属性管理器中有一个可扩展的属性,所以我可以轻松设置子属性,因为在父属性中组合在一起。这是我所做的工作的模式:

public partial class QViewer : UserControl
{
    private Shortcuts toolsShortcuts = new Shortcuts();
    private TestProp testProp = new TestProp();

    public Shortcuts ToolsShortcuts { get { return toolsShortcuts; } }
    public TestProp Test { get { return testProp; } }
}


public struct TestProp
{
    public bool DoIt;
    public DateTime Date;
}

public class Shortcuts
{
    Keys toolArrow = Keys.None;
    public Keys Arrow
    {
        get { return toolArrow; }
        set { ... }
    }
}
Run Code Online (Sandbox Code Playgroud)

}

当我在表单中插入我的自定义控件(在同一解决方案中使用另一个项目)并打开属性时,快捷方式测试都是灰色的,不可扩展,因此我无法在其中设置属性。
怎么了?有没有比创建类或结构更好的方法来对属性进行分组
感谢大家!

Chr*_*ers 5

IIRC你需要写一个TypeConverter来获取属性窗口来展开这些属性。

假设您对复杂属性使用以下类型:

[DescriptionAttribute("Expand to see the spelling options for the application.")]
public class SpellingOptions
{
    private bool spellCheckWhileTyping = true;
    private bool spellCheckCAPS = false;
    private bool suggestCorrections = true;

    [DefaultValueAttribute(true)]
    public bool SpellCheckWhileTyping 
    {
        get { return spellCheckWhileTyping; }
        set { spellCheckWhileTyping = value; }
    }

    [DefaultValueAttribute(false)]
    public bool SpellCheckCAPS 
    {
        get { return spellCheckCAPS; }
        set { spellCheckCAPS = value; }
    }

    [DefaultValueAttribute(true)]
    public bool SuggestCorrections 
    {
        get { return suggestCorrections; }
        set { suggestCorrections = value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

您的属性目前可能如下所示:

在此处输入图片说明

请注意,拼写检查选项属性是灰色的。

您需要创建一个 TypeConverter 来转换您的对象类型,以便它可以正确显示。.NET 框架提供了ExpandableObjectConverter类来简化此操作。

例如:

public class SpellingOptionsConverter:ExpandableObjectConverter 
{
    //...
}
Run Code Online (Sandbox Code Playgroud)

您需要按照以下步骤创建自定义 TypeConverter。

实现一个可以将字符串转换为 Point 的简单类型转换器

  1. 定义一个派生自 ExpandableObjectConverter(或 TypeConverter)的类。
  2. 覆盖指定转换器可以转换的类型的 CanConvertFrom 方法。此方法已重载。
  3. 重写实现转换的 ConvertFrom 方法。此方法已重载。
  4. 覆盖指定转换器可以转换为哪种类型的 CanConvertTo 方法。无需重写此方法即可转换为字符串类型。此方法已重载。
  5. 重写实现转换的 ConvertTo 方法。此方法已重载。
  6. 覆盖执行验证的 IsValid 方法。此方法已重载。

有关如何实现 TypeConverter 的更多信息,请查看以下 MSDN 页面:

如何:实现类型转换器

创建 TypeConverter 后,您可以将其应用于自定义类型。

[TypeConverterAttribute(typeof(SpellingOptionsConverter)),
 DescriptionAttribute("Expand to see the spelling options for the application.")]
public class SpellingOptions{ ... }
Run Code Online (Sandbox Code Playgroud)

一切都会好起来的:

在此处输入图片说明

我很快总结了 MSDN 上的一个 elobarate 示例。您可以在此处找到完整的演练:

充分利用 .NET Framework PropertyGrid 控件