How do I create a dashed border with rounded corners in WPF?

前端 未结 2 1088
借酒劲吻你
借酒劲吻你 2020-12-09 02:16

The Rectangle element has StrokeDashArray which allows it to be drawn with dashes, but it doesn\'t support rounded corners. The Border

2条回答
  •  醉梦人生
    2020-12-09 02:40

    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));
        }
    

提交回复
热议问题