C# 如何在 WPF 中创建带圆角的虚线边框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1048137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 06:57:22  来源:igfitidea点击:

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

c#wpfxamlwpf-controls

提问by GraemeF

The Rectangleelement has StrokeDashArraywhich allows it to be drawn with dashes, but it doesn't support rounded corners. The Bordercontrol supports nice thick lines with rounded corners, but will only draw solid lines.

Rectangle元素StrokeDashArray允许它用破折号绘制,但它不支持圆角。该Border控件支持带有圆角的漂亮粗线,但只会绘制实线。

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

虚线边框示例 http://img524.imageshack.us/img524/3186/dashedborder.png

采纳答案by Kent Boogaart

You are mistaken that Rectangledoes not support this:

你错了,Rectangle不支持这个:

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

enter image description here

在此处输入图片说明

回答by Vanathi Palanisamy

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.

WPF 边框控件不支持虚线。如果要为控件应用点/虚线边框,只需使用装饰器装饰控件即可。

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

这是示例装饰器类。这是任何 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'.

我的 xaml 中有一个简单的文本块,它包含在名为“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));
    }