我正在向屏幕添加动态元素。当元素填满我放入的容器时,我想要一个垂直滚动条出现,以便用户可以滚动浏览所有添加的元素。代码按预期执行。
问题在于,当元素添加到界面时,它们会以杂乱无章的方式添加。它们从网格元素的中间开始,然后向上移动。我希望它们被添加到控件的左上角,然后向右,一直向下,页面之间的行间距相等。然后当屏幕上有太多时,会出现滚动条。
以下是运行此测试的所有代码。在此先感谢您的帮助!
XAML:
<Window x:Class="GPWorkouts.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:GPWorkouts"
mc:Ignorable="d"
Title="MainWindow" Height="370" Width="1000" >
<Grid>
<StackPanel Orientation="Horizontal">
<StackPanel Width="500">
<StackPanel Orientation="Horizontal">
<Button Name="buttonAddNewPlayer" Content="Add New Player" Margin="5" Click="buttonAddNewPlayer_Click" />
</StackPanel>
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Hidden" Height="300">
<UniformGrid Columns="2" Name="playerContainer" ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.CanContentScroll="True" >
</UniformGrid>
</ScrollViewer>
</StackPanel>
</StackPanel>
</Grid>
</Window>
c#代码背后:
using log4net;
using System.Windows;
using System.Windows.Controls;
namespace GPWorkouts
{
public partial class MainWindow : Window
{
private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
int x = 1;
public MainWindow()
{
InitializeComponent();
}
private void buttonAddNewPlayer_Click(object sender, RoutedEventArgs e)
{
Button buttonDyno = new Button()
{
Content = x,
Width = 150,
Height = 32,
Margin = new Thickness(5),
};
x++;
playerContainer.Children.Add(buttonDyno);
}
}
}
答案 0 :(得分:2)
观察到的效果可以通过UniformGrid排列方法来解释。按钮从网格元素的中间开始,然后向上移动,因为在每个按钮添加后,UniformGrid的空间越来越小。
如果在Button属性中添加n Choose 2 = n*(n-1)/2 = O(n^2)
,则可以平滑效果。
但我建议使用不同的面板:WrapPanel
VerticalAlignment = VerticalAlignment.Top
<Grid>
<StackPanel Orientation="Horizontal">
<StackPanel Width="500">
<StackPanel Orientation="Horizontal">
<Button Name="buttonAddNewPlayer"
Margin="5"
Click="buttonAddNewPlayer_Click"
Content="Add New Player" />
</StackPanel>
<ScrollViewer Height="300"
HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Auto">
<WrapPanel Name="playerContainer"
Background="Wheat"
Orientation="Horizontal" />
</ScrollViewer>
</StackPanel>
</StackPanel>
</Grid>