Pregunta

I'm trying to center a Path so that its origin (0, 0) is located at the bottom, center of its container. Assume that the container is a Grid.


Example:

Tail of arrow is at the center-bottom of the box

Note: the tail of the arrow is at the origin (0, 0). The tail is centered horizontally but the overall arrow is skewed to the left. This is what I want to achieve regardless of which direction the arrow is pointing.


This needs to work for paths where the x and y coordinates are positive, negative, or a mixture of both.

How can this be done via XAML with the least markup?

¿Fue útil?

Solución 2

Here's what I ended up going with. Seems to work, but if there's a cleaner way to do this, I'd love to hear it:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Path Grid.Column="1"
          HorizontalAlignment="Left"
          VerticalAlignment="Bottom"
          StrokeThickness="1"
          Data="{Binding PathGeometry}" />
</Grid>

Otros consejos

Well... the position en in the bottom-middle depends on the container. Try something like this:

<Grid>
  <Path Stroke="Black"
        StrokeThickness="1"
        VerticalAlignment="Bottom"
        HorizontalAlignment="Center"
        Data="M 0,0 L -50,-70 L -50,-80" />
</Grid>

Here is what I have been using. Just draw your path wherever you want and afterwards translate it to the desired starting point. You can use Bindings to center it within the grid. This allows to place your geometry wherever you want within your grid.

<Grid>
    <Path Stroke="Black"
          StrokeThickness="1">
        <Path.Data>
            <PathGeometry>
                <!-- Your path geomrtry -->
            </PathGeometry>
        </Path.Data>
        <Path.RenderTransform>
            <TranslateTransform Y="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}, Path=ActualHeight, Converter={StaticResource widthAndHeightDivider}}"
                                X="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}, Path=ActualWidth, Converter={StaticResource widthAndHeightDivider}}"/>
        </Path.RenderTransform>
    </path>
</Grid>

And having the following converter, which divides the ActualWidth of the grid by to to get it centered:

public class WidthAndHeightDivider : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        double d = (double)value / 2.0;
        return d;
    }
}

I hope this helps!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top