将默认值设置为图像 "Public Property"
Set default value to an image "Public Property"
我尝试将默认值设置为 UserControl
的图像 Public Property
。我试图用一个变量来做到这一点,但我得到一个错误 Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.
Private Image_ As Image = My.Resources.MyImage
<Category("Appearance")> <DisplayName("Image")> <DefaultValue(Image_)> <Description("...")>
Public Property Image As Image
Get
Return NestedControl.Image
End Get
Set(ByVal value As Image)
NestedControl.Image = value
End Set
End Property
我也试过像这样设置默认值 <DefaultValue(GetType(Image), "My.Resources.MyImage")>
但是当我重置为 UserControl
的 属性 时它变成了 "None"!!!
有什么想法吗?
虽然 System.ComponentModel.DefaultValueAttribute
不支持此功能,但您可以使用 old-style ResetPropertyName 和 ShouldSerialize PropertyName方法实现同样的功能。
这在 Defining Default Values with the ShouldSerialize and Reset Methods 中有记载。
Imports System.ComponentModel
Public Class MyUserControl
Private Image_ As Image = My.Resources.MyImage
Public Sub New()
InitializeComponent()
ResetImage() ' set default
End Sub
<Category("Appearance")> <DisplayName("Image")> <Description("...")>
Public Property Image As Image
Get
Return NestedControl.Image
End Get
Set(ByVal value As Image)
NestedControl.Image = value
End Set
End Property
Public Sub ResetImage()
If Image IsNot Nothing Then Image.Dispose()
Image = Image_
End Sub
Public Function ShouldSerializeImage() As Boolean
Return (Image IsNot Image_)
End Function
End Class
我尝试将默认值设置为 UserControl
的图像 Public Property
。我试图用一个变量来做到这一点,但我得到一个错误 Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.
Private Image_ As Image = My.Resources.MyImage
<Category("Appearance")> <DisplayName("Image")> <DefaultValue(Image_)> <Description("...")>
Public Property Image As Image
Get
Return NestedControl.Image
End Get
Set(ByVal value As Image)
NestedControl.Image = value
End Set
End Property
我也试过像这样设置默认值 <DefaultValue(GetType(Image), "My.Resources.MyImage")>
但是当我重置为 UserControl
的 属性 时它变成了 "None"!!!
有什么想法吗?
虽然 System.ComponentModel.DefaultValueAttribute
不支持此功能,但您可以使用 old-style ResetPropertyName 和 ShouldSerialize PropertyName方法实现同样的功能。
这在 Defining Default Values with the ShouldSerialize and Reset Methods 中有记载。
Imports System.ComponentModel
Public Class MyUserControl
Private Image_ As Image = My.Resources.MyImage
Public Sub New()
InitializeComponent()
ResetImage() ' set default
End Sub
<Category("Appearance")> <DisplayName("Image")> <Description("...")>
Public Property Image As Image
Get
Return NestedControl.Image
End Get
Set(ByVal value As Image)
NestedControl.Image = value
End Set
End Property
Public Sub ResetImage()
If Image IsNot Nothing Then Image.Dispose()
Image = Image_
End Sub
Public Function ShouldSerializeImage() As Boolean
Return (Image IsNot Image_)
End Function
End Class