运行时代码无法访问用户控件属性的设计时更改

时间:2016-08-16 16:47:09

标签: vb.net winforms user-controls

基本上我尝试创建一个继承PictureBox的用户控件。我想对新图片框进行的更改之一是添加Opacity属性。

除了在设计时更改不透明度值时,一切似乎都能正常工作,该更改在运行时不会影响属性的实际值!

这是我的代码:

Private _opacity As Integer
Public Property Opacity() As Integer
    Get
        Return _opacity
    End Get
    Set(ByVal value As Integer)
        _opacity = value
        If Image IsNot Nothing Then
            MyBase.Image = ChangeOpacity(_image, value)
        End If
    End Set
End Property

Private _image As Image
Public Shadows Property Image() As Image
    Get
        Return _image
    End Get
    Set(ByVal value As Image)
        Dim bmp As Bitmap = value

        If bmp IsNot Nothing Then
            _image = ChangeOpacity(bmp, Opacity)
        Else
            _image = bmp
        End If
        MyBase.Image = _image
    End Set
End Property

好吧,我只是使用了一种不同的方法来避免问题。我重写了OnPaint方法,将ChangeOpacity方法的代码移到了它上面,并移除了阴影属性Image,因为我不再需要它了。现在问题已经消失。 但是我仍然很好奇为什么没有保存Opacity属性的设计时更改,以及为什么现在保存它?!

这是我的新工作代码。它可能对某人有所帮助:

Public Class Pic
    Inherits PictureBox

    Private _opacity As Integer
    Public Property Opacity() As Integer
        Get
            Return _opacity
        End Get
        Set(ByVal value As Integer)
            _opacity = value
        End Set
    End Property

    Protected Overrides Sub OnPaint(pe As PaintEventArgs)
        If Image IsNot Nothing Then
            Dim Gr As Graphics = pe.Graphics
            Dim colormatrix As New ColorMatrix
            colormatrix.Matrix33 = Opacity / 100
            Dim imgAttribute As New ImageAttributes
            imgAttribute.SetColorMatrix(colormatrix, ColorMatrixFlag.[Default], ColorAdjustType.Bitmap)
            Gr.DrawImage(Image, New Rectangle(0, 0, Image.Width, Image.Height), 0, 0, Image.Width, Image.Height,
            GraphicsUnit.Pixel, imgAttribute)
        Else
            MyBase.OnPaint(pe)
        End If
    End Sub

End Class

1 个答案:

答案 0 :(得分:0)

Yes it's called and used but with the default Opacity value no matter what the design time value is!

变量在设计者定义的单个方法中被赋予其设计时值。设计者可能首先初始化Image变量。