【问题标题】:Custom Border in a WPF Label [duplicate]WPF标签中的自定义边框[重复]
【发布时间】:2023-03-12 20:25:02
【问题描述】:

我需要构建一个像这样的自定义 WPF 控件

由于我是 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) 为什么我的角移动了一个像素(不是真正正确链接)?

【问题讨论】:

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


    【解决方案1】:

    最好的做法是创建您自己的 Decorator 类,而不是使用 Border 类/控件(这基本上就是 Border 的含义)。

    【讨论】:

    • 这个控件的继承呢?边框和装饰器不是继承的......而且,我不知道如何设置边框,但角落是可见的;
    • 如果您查看 Border.cs 的源代码,您会发现它覆盖了 ArrangeOverrideMeasureOverrideOnRender 方法,这些方法是创建您自己的类型的关键Decorator.
    【解决方案2】:

    我尝试回答您的问题:

    更新: 回复您的评论:

    a) 要创建仅在角落可见的边框,您可以尝试使用带有不透明蒙版的简单边框(但尚未对此进行测试)

    b) 我想您使用的方法在您的情况下是可以的,(但是,如果您制作了模板化控件,这将不是问题;))。

    c) 对不起,我的错。您可以尝试将StartLineCapEndLineCap 设置为PenLineCap.RoundPenLineCap.Square 值。更多信息可以在 MSDN 上找到:http://msdn.microsoft.com/en-us/library/system.windows.media.pen.aspx

    【讨论】:

    • 卢卡斯,感谢您的回答。 a)我不知道如何设置边框,但角落是可见的; b) -; c) 据我了解,LineJoin 用于多角线,但我画了 8 条独立线...*
    • 没问题,希望我的回答对你有所帮助。我已对其进行了更新,以包含对您评论的回答。
    猜你喜欢
    • 2020-03-09
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 2021-04-14
    相关资源
    最近更新 更多