WPF标签中的自定义边框

时间:2012-03-07 19:11:54

标签: .net wpf vb.net custom-controls paintcomponent

我需要构建一个这样的自定义WPF控件 enter image description here

由于我是WPF的新手,我使用了以下代码(对不起VB.NET)

Public Class TextPlaceholder
  Inherits System.Windows.Controls.Label

  Const CustomBorderWidth As Integer = 2

  Public Sub New()
    MyBase.New()
    Me.BorderBrush = SystemColors.ActiveBorderBrush
  End Sub

  Protected Overrides Sub OnRender(drawingContext As System.Windows.Media.DrawingContext)
    MyBase.OnRender(drawingContext)

    Dim pointTopLeft As New Point(-1, -1)
    Dim pointTopRight As New Point(Me.ActualWidth, -1)
    Dim pointBottomLeft As New Point(-1, Me.ActualHeight)
    Dim pointBottomRight As New Point(Me.ActualWidth, Me.ActualHeight)

    Dim myPen As New Pen(Me.BorderBrush, CustomBorderWidth)
    drawingContext.DrawLine(myPen, pointTopLeft, New Point(pointTopLeft.X + 5, pointTopLeft.Y))
    drawingContext.DrawLine(myPen, pointTopLeft, New Point(pointTopLeft.X, pointTopLeft.Y + 5))

    drawingContext.DrawLine(myPen, pointTopRight, New Point(pointTopRight.X - 5, pointTopRight.Y))
    drawingContext.DrawLine(myPen, pointTopRight, New Point(pointTopRight.X, pointTopRight.Y + 5))

    drawingContext.DrawLine(myPen, pointBottomLeft, New Point(pointBottomLeft.X + 5, pointBottomLeft.Y))
    drawingContext.DrawLine(myPen, pointBottomLeft, New Point(pointBottomLeft.X, pointBottomLeft.Y - 5))

    drawingContext.DrawLine(myPen, pointBottomRight, New Point(pointBottomRight.X - 5, pointBottomRight.Y))
    drawingContext.DrawLine(myPen, pointBottomRight, New Point(pointBottomRight.X, pointBottomRight.Y - 5))
  End Sub

End Class

现在

1)这是最好的方法吗,考虑到我会继承那个控件并且在继承的控件上需要相同的边框
2)是否可以像我一样指定BorderBrush的默认值(不透明)? 3)为什么我的角落被一个像素移动(没有真正正确的链接)?

2 个答案:

答案 0 :(得分:2)

更好的做法是使用Border类/控件创建自己的Decorator类(基本上是Border)。

答案 1 :(得分:0)

我尝试回答你的问题:

<强>更新 您的评论的答案:

a)创建仅在角落可见的边框,你可以尝试使用带有不透明蒙版的简单边框(虽然还没有测试过)

b)我认为你使用的方法在你的情况下是可以的(但是,如果你做了一个模板控制,这不会是一个问题;))。

c)抱歉,我的错误。您可以尝试将StartLineCapEndLineCap设置为PenLineCap.RoundPenLineCap.Square值。有关详细信息,请访问MSDN:http://msdn.microsoft.com/en-us/library/system.windows.media.pen.aspx