32

The Rectangle element has StrokeDashArray which allows it to be drawn with dashes, but it doesn't support rounded corners. The Border control supports nice thick lines with rounded corners, but will only draw solid lines.

What's the best way to achieve a dashed border with rounded corners, with any control?

Example of dashed border http://img524.imageshack.us/img524/3186/dashedborder.png

lisp
  • 4,138
  • 2
  • 26
  • 43
GraemeF
  • 11,327
  • 5
  • 52
  • 76

2 Answers2

73

You are mistaken that Rectangle does not support this:

<Rectangle StrokeDashArray="0.5 1.0 0.3" Stroke="Black" StrokeThickness="2" RadiusX="10" RadiusY="10"/>

enter image description here

Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
  • Your image link seems to have broken. If you still have the original image, please reupload it to stack.imgur, or just edit your answer to make it work without the image. Thanks. – Ilmari Karonen Jul 27 '15 at 09:48
9

WPF Border control does not support dashed lines. If you want to apply a dotted/dashed border for a control, you can simply decorate the control with an adorner.

Here is the sample adorner class. This is a generic adorner for any UIelement.

class DottedLineAdorner : Adorner
{
    public UIElement AdornedElement { get; set; }

    public DottedLineAdorner(UIElement adornedElement) : base(adornedElement)
    {
        AdornedElement = adornedElement;
    }

    protected override void OnRender(DrawingContext drawingContext)
    {
        Size eltSize = (AdornedElement as FrameworkElement).DesiredSize;
        Pen pen = new Pen(Brushes.Blue, 2) { DashStyle = DashStyles.DashDot };
        drawingContext.DrawRoundedRectangle(null, pen, new Rect(0, 0, eltSize.Width, eltSize.Height), 10, 10);
    }
}

I have a simple textblock in my xaml and it is contained in a grid named 'LayoutGrid'.

Now, the border can be applied in the code behind

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        AdornerLayer.GetAdornerLayer(LayoutGrid).Add(new DottedLineAdorner(textblock));
    }