简体   繁体   English

如何在WPF中获得动态添加的控件的位置?

[英]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. 提前致谢。

You need to measure and arrange the Grid before you can get the actual location of the Button : 在获取Button的实际位置之前,您需要测量并布置Grid

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);
}

Adding controls to a grid without specifying column or row will position them all at the same location in the grid (0,0). 在不指定列或行的情况下将控件添加到网格中会将它们全部定位在网格(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. 使用StackPanel垂直或水平放置控件。 You can also have a look at the DockPanel 您也可以看看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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM