我遇到了在运行时获取动态添加按钮位置的问题。请找到以下代码。
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;
}
提前致谢。
答案 0 :(得分:1)
您需要先测量并排列Grid
,然后才能获得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);
}
答案 1 :(得分:0)
在不指定列或行的情况下向网格添加控件会将它们全部放置在网格中的相同位置(0,0)。使用另一个父控件以不同的方式定位控件或指定网格中的列和行。
使用<div class="col-lg-12">
<form class="well form-horizontal" id="contact_form" ng-submit="submitApplication()" name="form">
<fieldset>
<!-- some more fields -->
<div class="form-group">
<label class="col-md-4 control-label"></label>
<div class="col-md-2">
<button type="submit" class="btn btn-primary"> Submit <span class="glyphicon glyphicon-send"></span></button>
<!-- <button class="btn btn-primary" ng-click="submitApplication()"> Submit <span class="glyphicon glyphicon-send"></span></button> -->
</div>
<div>
<button class="btn btn-warning" ng-click="saveApplication()"> Save <span class="glyphicon glyphicon-floppy-disk"></span></button>
</div>
</div>
</fieldset>
</form>
垂直或水平放置控件。您还可以查看StackPanel
横向:
按钮 按钮 按钮
DockPanel
或垂直:
按钮
按钮
按钮
<StackPanel Orientation="Horizontal">
<Button>Btn1</Button>
<Button>Btn2</Button>
<Button>Btn3</Button>
</StackPanel>