在尝试编写自定义控件时,我遇到了 System.Windows.Forms.TextFormatFlags 枚举与 Visual Studio (2005/2008) 编辑器结合使用的问题。这个问题的原因似乎来自这个枚举有多个映射到零值的成员。选择这些成员中的任何一个(GlyphOverhangPadding、Left、Default、Top)都会导致编辑器将属性设置为
this.customControl.TextFormatFlags = System.Windows.Forms.TextFormatFlags.GlyphOverhangPadding;
代码按预期编译。但是,从编辑器的属性网格中选择任何非零成员(例如“Right”)会导致以下结果:
this.customControl.TextFormatFlags = System.Windows.Forms.TextFormatFlags.Left, Default, Top, Right;
显然这不会编译。选择多个非零成员(通过 UITypeEditor,例如“Right | Bottom”)会导致以下结果:
this.customControl.TextFormatFlags = ((System.Windows.Forms.TextFormatFlags)((System.Windows.Forms.TextFormatFlags.Left, Default, Top, Right | System.Windows.Forms.TextFormatFlags.Left, Default, Top, Bottom)));
如您所见,编辑器将四个零值成员中的三个添加到任何选定项。
如果您希望重现此问题:
- 在 Visual Studio 2005/2008(Windows 窗体应用程序)中创建一个新项目
- 将自定义控件添加到项目中。
将私有字段和公共属性添加到新类:
私有 TextFormatFlags tff = TextFormatFlags.Default;
public TextFormatFlags TFFProperty { get { return this.tff; } 设置 { this.tff = 值;} }
编译代码
- 在设计器中打开 Form1 并将 CustomControl1 添加到其中
- 代码编译得很好
- 现在在编辑器的 PropertyGrid 中打开 CustomControl1 的属性
- 您应该在“杂项”部分下看到 TFFProperty
- 该属性提供多个值,其中大部分包含逗号。
- 选择任何带逗号的值(例如“Left、Default、Top、HorizontalCenter)会导致代码不可编译
如果您使用 Flags 属性创建自己的枚举并添加多个映射到零的成员(这是一种格式错误的标志枚举?),也会发生同样的情况。我已经验证这不是我正在使用的 UITypeEditor 的错误(不使用 UITypeEditor 也会出现同样的问题)。我试图用转换器来规避这个问题,但到目前为止没有成功。如果有人对如何解决这个问题有任何想法,我会很高兴听到他们的声音。