2016-10-02 89 views
0

我嘗試使用BorderColor屬性創建標籤,但它不起作用。我在表單應用程序中創建了該標籤的即時對象,並嘗試更改BorderColor,但沒有發生任何事情。 這是我的代碼:使用BorderColor屬性創建自定義標籤

Public Class MyLabel 
Inherits Label 

Private _BorderColor As Color 
Dim e As New PaintEventArgs(Me.CreateGraphics, Me.DisplayRectangle) 

Public Property BorderColor As Color 
    Get 
     Return _BorderColor 
    End Get 
    Set(value As Color) 
     _BorderColor = value 
     CreateBorder(value) 
    End Set 
End Property 

Private Sub CreateBorder(ByVal value As Color) 
    Dim g As Graphics = Me.CreateGraphics 
    Dim p As Pen = New Pen(value, 2) 
    g.DrawRectangle(p, Me.DisplayRectangle) 
End Sub 

Private Sub MyLabel_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint 
    CreateBorder(_BorderColor) 
End Sub 

末級

回答

1

不,不,雙沒有。您不要撥打CreateGraphics。通過Paint事件向您提供了一個Graphics對象,並使用該對象。另外,您不會在自定義控件中處理Paint事件,而是會覆蓋OnPaint方法。此外,如果你有一個方法來完成繪圖,例如CreateBorder,那麼除了OnPaint方法外,你不能從任何地方調用它。如果您想確保邊界在下一個事件中重新繪製,那麼請致電Invalidate。例如。

Public Class BorderedLabel 
    Inherits Label 

    Private _borderColor As Color 

    Property BorderColor As Color 
     Get 
      Return _borderColor 
     End Get 
     Set 
      _borderColor = Value 
      Invalidate() 
     End Set 
    End Property 

    Protected Overrides Sub OnPaint(e As PaintEventArgs) 
     MyBase.OnPaint(e) 

     Using p As New Pen(BorderColor, 2) 
      e.Graphics.DrawRectangle(p, DisplayRectangle) 
     End Using 
    End Sub 

End Class 
+0

......你也不會改變PaintEventArgs的 – Plutonix

+1

使用的Invalidate()從來沒有,刷新()。 –

+0

@HansPassant,我想說,在應用程序代碼中,如果您特別想確保現在進行重繪,則可以調用'Refresh'。儘管在控制代碼中,你可能是正確的,「Invalidate」更合適。我已經做了上面的改變。 – jmcilhinney

-1

感謝...現在它的工作 這是新代碼:

Public Class MyLabel 
Inherits Label 

Private _BorderColor As Color 
Private _BorderSize As Single = 1.0F 

Public Property BorderColor As Color 
    Get 
     Return _BorderColor 
    End Get 
    Set(value As Color) 
     _BorderColor = value 
     Refresh() 
    End Set 
End Property 

Public Property BorderSize As Single 
    Get 
     Return _BorderSize 
    End Get 
    Set(value As Single) 
     _BorderSize = value 
    End Set 
End Property 

Private Sub CreateBorder(ByVal value As Color, ByVal e As PaintEventArgs) 
    Dim g As Graphics = e.Graphics 
    Dim p As Pen = New Pen(value, _BorderSize) 
    g.DrawRectangle(p, Me.DisplayRectangle) 
End Sub 

Private Sub MyLabel_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint 
    CreateBorder(_BorderColor, e) 
End Sub 

末級

+0

這和jimcilhinney先生的答案沒有什麼區別。您應該非常友好,並單擊該答案旁邊的複選標記。 – Plutonix

+0

當然,你是對的,但我找不到幫助的選中標記,請再次顯示.... thanka –