WPF虚线边框控件

6
我想创建一个从Border继承的控件,它可以简单地允许我指定StrokeDashArray以虚线绘制边框线。
我不想使用'google'建议的hack,例如矩形等,因为我想要边框控件给出的灵活性。
但是,我没有创建自定义控件的经验,也不知道从哪里开始?
你可以指点我一下吗?
谢谢!

边框不是控件,而是框架元素。最好通过属性来解决这个问题。 - H H
1
这里提出的解决方案有什么问题吗?https://dev59.com/lXNA5IYBdhLWcg3wNrAy - Matt Hamilton
如果不允许我只绘制边框的某些边,例如将strokethickness =“1,0,0,1”设置仍会绘制一个矩形,而不会跳过顶部和右侧。 - Jon
2个回答

14

虽然还不是最优解,但尝试使用来自链接的Matt Hamilton的解决方案作为VisualBrush

使用带有虚线RectangleSolidColorBrushVisualBrush进行比较

enter image description here

<Border BorderThickness="3,2,1,0" CornerRadius="10">
    <Border.BorderBrush>
        <VisualBrush>
            <VisualBrush.Visual>
                <Rectangle StrokeDashArray="1.0 1.0"
                           Stroke="Red"
                           StrokeThickness="{Binding RelativeSource={RelativeSource AncestorType={x:Type Border}},
                                                     Path=BorderThickness,
                                                     Converter={StaticResource ThicknessMaxConverter}}"
                           RadiusX="{Binding RelativeSource={RelativeSource AncestorType={x:Type Border}}, Path=CornerRadius.TopRight}"
                           RadiusY="{Binding RelativeSource={RelativeSource AncestorType={x:Type Border}}, Path=CornerRadius.BottomLeft}"
                           Width="{Binding RelativeSource={RelativeSource AncestorType={x:Type Border}}, Path=ActualWidth}"
                           Height="{Binding RelativeSource={RelativeSource AncestorType={x:Type Border}}, Path=ActualHeight}"/>
            </VisualBrush.Visual>
        </VisualBrush>
    </Border.BorderBrush>
</Border>

ThicknessMaxConverter

public class ThicknessMaxConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Thickness thickness = (Thickness)value;
        double horizontalMax = Math.Max(thickness.Left, thickness.Right);
        double verticalMax = Math.Max(thickness.Top, thickness.Bottom);
        return Math.Max(horizontalMax, verticalMax);
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

2
抱歉有点晚了,但这是一个使用 StrokeDashArray 属性的 WPF 解决方案。
ellipse Ellipse = new Ellipse();
/*code to change ellipse size, margin, color, etc*/
ellipse.StrokeDashArray=new DoubleCollection(new double[] {4, 3})
//First number is the dash length, second number the dash gap

我知道这是c#代码而不是XML,但是属性仍然相同。如果你想更好地控制破折号,请使用其他在这里找到的“Stroke”属性。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接