将复选框添加到UniformGrid

我试图动态添加复选框到wpf中的uniformgrid。 但看起来网格没有为它们分配足够的空间,所以它们都有点相互叠加。 这就是我在代码中添加它们的方法:

foreach (string folder in subfolders) { PathCheckBox chk = new PathCheckBox(); chk.Content = new DirectoryInfo(folder).Name; chk.FullPath = folder; chk.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch; chk.VerticalAlignment = System.Windows.VerticalAlignment.Stretch; unfiformGridSubfolders.Children.Add(chk); } 

这就是我的XAML外观(我将uniformgrid放在scrollviewer中)

    

这就是它在程序中的表现:

在此处输入图像描述

我只是希望每个checkBox都有足够的空间,以便可以完全读取内容。

必须动态添加UI元素吗? 你不能只预定义你的CheckBox模板并添加CheckBox.Content吗? 如果可以,那么定义一个包含CheckBox.ContentObservableCollection ,如下所示:

 public ObservableCollection SubfolderNames { get; set; } 

然后定义ItemsControl并将其ItemsSource绑定到您的集合:

                     

这样,所有项目具有与共享大小组相同的宽度,而且因为它们的大小为Auto ,它们也将调整为最大的CheckBox.Content

我建议使用像WrapPanel这样的东西

那么我怎么能这样做,每个单元格的大小都是具有最大内容的checkBox?

使用UniformGrid您必须手动浏览每个复选框,检查其大小,并将Uniform Grid.Columns修改为类似Math.Floor(Grid.CurrentWidth / CheckBoxMaxWidth)

UniformGridRowsColumns属性都设置为零时, UniformGrid尝试在UniformGrid中布置元素,而不考虑元素的大小。 我会编写一个面板,根据您的需要布置您的元素,如下所示。 只需在XAML中使用MyPanel而不是UniformGrid

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; namespace MyNamespace { class MyPanel : Panel { int columns; int rows; protected override Size MeasureOverride (Size constraint) { Size childConstraint = constraint; double maxChildDesiredWidth = 0.0; double maxChildDesiredHeight = 0.0; if (InternalChildren.Count > 0) { for (int i = 0, count = InternalChildren.Count; i < count; ++i) { UIElement child = InternalChildren[i]; // Measure the child. child.Measure (childConstraint); Size childDesiredSize = child.DesiredSize; if (maxChildDesiredWidth < childDesiredSize.Width) { maxChildDesiredWidth = childDesiredSize.Width; } if (maxChildDesiredHeight < childDesiredSize.Height) { maxChildDesiredHeight = childDesiredSize.Height; } } columns = (int)(constraint.Width / maxChildDesiredWidth); rows = (int)(InternalChildren.Count / columns + 0.5); } else { columns = 0; rows = 0; } return new Size ((maxChildDesiredWidth * columns), (maxChildDesiredHeight * rows)); } protected override Size ArrangeOverride (Size arrangeSize) { Rect childBounds = new Rect (0, 0, arrangeSize.Width / columns, arrangeSize.Height / rows); double xStep = childBounds.Width; double xBound = arrangeSize.Width - 1.0; childBounds.X += 0; foreach (UIElement child in InternalChildren) { child.Arrange (childBounds); if (child.Visibility != Visibility.Collapsed) { childBounds.X += xStep; if (childBounds.X >= xBound) { childBounds.Y += childBounds.Height; childBounds.X = 0; } } } return arrangeSize; } } }