Anjali
Anjali

Reputation: 1718

How to get the position of a dynamically added control in WPF?

I am facing an issue to get the position of a dynamically added button during runtime. Please find the below code.

foreach (string subfolder in Directory.GetDirectories(path))
        {
            Button btnSubfolder = new Button();
            btnSubfolder.Name = "btnsubfolder" + column.ToString();
            btnSubfolder.Content = subfolder.Substring(subfolder.LastIndexOf("\\") + 1);
            btnSubfolder.Margin = new Thickness(15, 15, 10, 0);
            btnSubfolder.Width = 200;
            btnSubfolder.Height = 50;
            btnSubfolder.HorizontalAlignment = HorizontalAlignment.Left;
            btnSubfolder.SetValue(Grid.ColumnProperty, column);
            grdsbFolders.Children.Add(btnSubfolder);
            var location = btnSubFolder.PointToScreen(new Point(0, 0)); //here i am getting the same position for all the added controls;
        }

Thanks in advance.

Upvotes: 0

Views: 814

Answers (2)

mm8
mm8

Reputation: 169390

You need to measure and arrange the Grid before you can get the actual location of the Button:

foreach (string subfolder in Directory.GetDirectories(path))
{
    Button btnSubfolder = new Button();
    btnSubfolder.Name = "btnsubfolder" + column.ToString();
    btnSubfolder.Content = subfolder.Substring(subfolder.LastIndexOf("\\") + 1);
    btnSubfolder.Margin = new Thickness(15, 15, 10, 0);
    btnSubfolder.Width = 200;
    btnSubfolder.Height = 50;
    btnSubfolder.HorizontalAlignment = HorizontalAlignment.Left;
    btnSubfolder.SetValue(Grid.ColumnProperty, column);
    grdsbFolders.Children.Add(btnSubfolder);

    grdsbFolders.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
    grdsbFolders.Arrange(new Rect());
    var location = btnSubfolder.TranslatePoint(new Point(0, 0), grdsbFolders);
}

Upvotes: 2

Chrille
Chrille

Reputation: 1453

Adding controls to a grid without specifying column or row will position them all at the same location in the grid (0,0). Use another parent control to position the controls in a different way or specify the column and row in the grid.

Use StackPanel to position the controls either vertically or horizontally. You can also have a look at the DockPanel

Horizontal:

Button Button Button

<StackPanel Orientation="Horizontal">
  <Button>Btn1</Button>
  <Button>Btn2</Button>
  <Button>Btn3</Button>
</StackPanel>

or vertical:

Button
Button
Button

<StackPanel Orientation="Vertical">
  <Button>Btn1</Button>
  <Button>Btn2</Button>
  <Button>Btn3</Button>
</StackPanel>

Upvotes: 0

Related Questions