簡單的解決方案
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
好的,謝謝你的提示,我會做 –