Simos Sigma
Simos Sigma

Reputation: 978

Set default value to an image "Public Property"

I try to set default value to an image Public Property of a UserControl. I tried to do that with a variable but I get an error 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

I also tried to set default value like this <DefaultValue(GetType(Image), "My.Resources.MyImage")> but when I do reset to UserControl's property it turns to "None"!!!

Any idea?

Upvotes: 0

Views: 472

Answers (1)

TnTinMn
TnTinMn

Reputation: 11801

While the System.ComponentModel.DefaultValueAttribute does not support this, you can use the old-style ResetPropertyName and ShouldSerializePropertyName methods to achieve the same function.

This is documented in 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

Upvotes: 1

Related Questions