JVimes JVimes - 1 year ago 61
C# Question

Fit Border around arbitrary Path

I have a Path based on a group of rectangle/ellipse Geometry. When I put an auto-sized Border around it, the border shrinks to fit the RectangleGeometry but does something weird with the EllipseGeometry, as shown below. Anyone know how to fix it so the Border (shown in blue) fits snugly around the whole thing?

Ultimately, I want a Border or a Panel that fits an arbitrary, runtime-generated Path (including the stroke thickness), and I need the geometry size maintained.


Sample code:

<Border BorderBrush="Blue" BorderThickness="2"
HorizontalAlignment="Center" VerticalAlignment="Center">
<Path Stroke="Orange" StrokeThickness="5" Fill="Red">
<EllipseGeometry Center="-10,-10" RadiusX="12" RadiusY="12" />
<EllipseGeometry Center="70,0" RadiusX="70" RadiusY="10">
<RotateTransform Angle="-25" CenterX="50" CenterY="0" />
<RectangleGeometry Rect="0,0,100,100" />

Answer Source

You may set the Path's Stretch property and bind its Width to the Width of the Bounds of the Geometry:

<Path ... Stretch="Uniform"
          Width="{Binding Data.Bounds.Width, RelativeSource={RelativeSource Self}}">

However, that doesn't maintain size if there's a stroke thickness. An alternative that does: put the Border into a Canvas (which does not resize its child elements at all), and do not set the Path's Width:

    <Border BorderBrush="Blue" BorderThickness="2">
        <Path ... Stretch="Uniform">
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download