简单的解决方案
foreach (var user in usersFromDb)
{
var canvas = new Canvas
{
Width = 1080,
Height = 70
};
var canavasThickness = canvas.Margin;
canavasThickness.Top = spacer;
canvas.Margin = canavasThickness;
canvas.VerticalAlignment = VerticalAlignment.Top; // <------ THIS IS THE SOLUTION <-------- //
UserGrid.Children.Add(canvas);
var button = new Button
{
Width = 1080,
Height = 70,
FontSize = 20,
Content = $"{user.Name} {user.Surname}",
Background = Brushes.Azure,
Foreground = Brushes.Black
};
canvas.Children.Add(button);
spacer += 150;
}
请考虑依赖属性 - 至少绑定您的数据......
public partial class UserView : UserControl
{
public ObservableCollection<User> UserViewCollection
{
get { return (ObservableCollection<User>)GetValue(UserViewCollectionProperty); }
set { SetValue(UserViewCollectionProperty, value); }
}
// Using a DependencyProperty as the backing store for UserViewCollection. This enables animation, styling, binding, etc...
public static readonly DependencyProperty UserViewCollectionProperty =
DependencyProperty.Register("UserViewCollection", typeof(ObservableCollection<User>), typeof(UserView), new PropertyMetadata(null, OnCollectionChanged));
private static void OnCollectionChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
UserView self = d as UserView;
if(self != null)
{
self.UpdateButtonsInCodeBehind(args.NewValue as ObservableCollection<User>);
}
}
public UserView()
{
InitializeComponent();
}
private void UpdateButtonsInCodeBehind(ObservableCollection<User> collection)
{
if(collection != null)
{
UserGrid.Children.Clear();
var spacer = 0;
foreach (var user in collection)
{
var canvas = new Canvas
{
Width = 1080,
Height = 70
};
var canavasThickness = canvas.Margin;
canavasThickness.Top = spacer;
canvas.Margin = canavasThickness;
canvas.VerticalAlignment = VerticalAlignment.Top; // <------ THIS IS THE SOLUTION <-------- //
UserGrid.Children.Add(canvas);
var button = new Button
{
Width = 1080,
Height = 70,
FontSize = 20,
Content = $"{user.Name} {user.Surname}",
Background = Brushes.Azure,
Foreground = Brushes.Black
};
canvas.Children.Add(button);
spacer += 150;
}
}
}
}
现在可以绑定集合 - 像一个ItemsControl
。如果你不知道这意味着什么 - 请使用WPF检查MVVM。教程链接here
简单的解决方案也可以工作,但它的丑陋!为什么不重写ListViewTemplate ...
看起来像你的UserControl在窗口中垂直居中。除此之外,Margins做布局通常是一个坏主意。不要将按钮放在网格中的Canvas中,而应将它们放入StackPanel中,该设计用于垂直或水平布局。您还应该考虑使用ItemsControl而不是UserControl。 ItemsControl是显示项目集合的基础控件。如果您还需要选择项目的功能,请使用ListBox或ListView。开始阅读这里:[数据模板概述](https://msdn.microsoft.com/en-us/library/ms742521(v = vs.110).aspx)。 – Clemens
好的,谢谢你的提示,我会做 –