Search code examples
wpfpathpathgeometry

Change element location WPF


How can I change the location element (Line) in C# code?

<Grid x:Name="SetShipsGrid">
        <Path Name="Line" Stroke="red" StrokeThickness="1" >
            <Path.Data >
                <GeometryGroup>
                    <LineGeometry StartPoint="50,50" EndPoint="350,50"></LineGeometry>
                </GeometryGroup>
            </Path.Data>
        </Path>
</Grid>

Solution

  • You can just bind the Start and End points to public properties

    Xaml:

        <Grid x:Name="SetShipsGrid">
            <Path Name="Line" Stroke="red" StrokeThickness="1" >
                <Path.Data >
                    <GeometryGroup>
                        <LineGeometry StartPoint="{Binding StartPoint}" EndPoint="{Binding EndPoint}" />
                    </GeometryGroup>
                </Path.Data>
            </Path>
        </Grid>
    

    Code:

        private Point _startPoint = new Point(5, 5);
        private Point _endPoint = new Point(100, 100);
    
        public Point StartPoint
        {
            get { return _startPoint; }
            set { _startPoint = value; NotifyPropertyChanged(); }
        }
    
        public Point EndPoint
        {
            get { return _endPoint; }
            set { _endPoint = value; NotifyPropertyChanged(); }
        }