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