PropertyGrid - 如何设置属性的默认颜色值

时间:2015-08-29 16:30:27

标签: vb.net propertygrid

我为PropertyGrid定义了一个Class。其中两个属性是TextColor和TextFont。我无法直接或通过定义常量来设置默认值。

Private Const dTextColor As Color = Color.Black 

不允许我设置值。设置默认字体常量时也存在同样的问题。

3 个答案:

答案 0 :(得分:1)

您无法在.net。

中将constcolor一起使用
  

用户定义的类型,包括类,结构和数组,不能是常量。

有关详细信息,请MSDN

  

常量声明中指定的类型必须是sbyte,byte,short,ushort,int,uint,long,ulong,char,float,double,decimal,bool,string,enum-type或reference-type

而不是使用Private Const dTextColor As Color = Color.Black,您可以使用Private readonly dTextColor As Color = Color.Black

答案 1 :(得分:1)

当属性不是简单类型时,您需要添加ShouldSerialize and Reset方法。以下是默认值为Pink的示例:

Public Class Foo

    Public Property TextColor As Color = Color.Pink

    Private Function ShouldSerializeTextColor() As Boolean
        Return (Me.TextColor <> Color.Pink)
    End Function

    Private Sub ResetTextColor()
        Me.TextColor = Color.Pink
    End Sub

End Class

enter image description here

答案 2 :(得分:0)

虽然Bjørn-Roger的解决方案可能是最好的,但您也可以使用DefaultValue属性。其中一个重载允许您指定默认值的类型(System.Type)以及默认值。但是“默认值”参数是一个字符串,但主系统类似乎能够将其转换为正确的值。

<DefaultValue(GetType(Color), "Black")> _
Public Property TextColor As Color = Color.Black