![](/img/trans.png)
[英]How to get height and width of dynamically designed user control while added in wpf canvas control?
[英]How to get the position of a dynamically added control in WPF?
我在获取运行时动态添加按钮的位置时遇到了问题。 请找到下面的代码。
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;
}
提前致谢。
在获取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);
}
在不指定列或行的情况下将控件添加到网格中会将它们全部定位在网格(0,0)中的同一位置。 使用另一个父控件以其他方式放置控件,或在网格中指定列和行。
使用StackPanel
垂直或水平放置控件。 您也可以看看DockPanel
水平:
按钮 按钮 按钮
<StackPanel Orientation="Horizontal">
<Button>Btn1</Button>
<Button>Btn2</Button>
<Button>Btn3</Button>
</StackPanel>
或垂直:
纽扣
纽扣
纽扣
<StackPanel Orientation="Vertical">
<Button>Btn1</Button>
<Button>Btn2</Button>
<Button>Btn3</Button>
</StackPanel>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.