WPF: How to autosize Path to its container?

前端 未结 4 561
闹比i
闹比i 2021-01-17 09:37

I have a Path that must resize to its StackPanel container.


    

        
相关标签:
4条回答
  • 2021-01-17 10:03

    Any reason why you're not using a ViewBox for this? That will shrink or grow the path as needed. If you don't want it scaled, but rather clipped, then set the clipping mode to be restricted to the control's bounding box. (I'd wrap the path in a ContentPresenter for that.)

    0 讨论(0)
  • 2021-01-17 10:13

    I changed the Stackpanel to Grid and Stretch property of the Path to Fill.

    <Grid x:Name="TrackSurface"> 
    <Path Fill="AliceBlue" 
    Stretch="Fill"
          Stroke="Black" StrokeThickness="1" 
          Data="M148,28 C221,133 110.50025,119.5 110.50025,119.5 L124.50016,68.5 z"> 
    </Path> 
    

    0 讨论(0)
  • 2021-01-17 10:18

    If you want this with a constant stroke width that isn't scaled, you can use a custom Shape. Shapes in WPF effectively encapsulate scaling a geometry and applying a stroke afterwards, which means you can have a scaled path that also always has the same stroke width.

    Creating a shape is quite easy:

    public class MyShape : Shape
    {
      public override Geometry DefiningGeometry
      {
        get
        {
          // Create your geometry here
        }
      }
    }
    
    0 讨论(0)
  • 2021-01-17 10:22

    Ensure that your path is smaller than your StackPanel.

    Easiest way for a very easy path will be to move the comma in every number (i.e. divide everything by 10 or 100 in TranslateZ), or for more complicated paths add a LayoutTransform (lower the scaling factor as needed):

    <StackPanel x:Name="TrackSurface">
        <Path Fill="AliceBlue" Stroke="Black" StrokeThickness="1" 
              Data="{StaticResource TranslateZ}">
              <Path.LayoutTransform>
                   <ScaleTransform ScaleX="0.1" ScaleY="0.1"/>
              </Path.LayoutTransform>
        </Path>
    </StackPanel>
    

    Some Remarks:

    I had a similar problem, with a button template containing a path. The button's "auto" size was determined by the path, because the path had the largest dimensions of the template content.

    This in itself might not turn out as a problem, because if you specify the button's height/width, or if the button's Horizontal-/VerticalAlignment is set to stretch, of course the path will scale.

    For other values of Horizontal-/VerticalAlignment however, the button size gets determined by the amount of space required by its content, which in my case resulted in a button with the path's original dimensions.

    0 讨论(0)
提交回复
热议问题