向UniformGrid添加复选框 [英] Adding checkBoxes to UniformGrid
问题描述
我试图动态添加复选框到wpf的uniformgrid。
但是它看起来像网格没有分配足够的空间,所以他们都喜欢躺在彼此。
这是我如何在代码中添加它们:
I am trying to dynamically add checkboxes to an uniformgrid in wpf. But it looks like the grid doesn't allocate them enough space and so they all kinda lay over each other. This is how I add them in code behind:
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看起来(我把均匀网格放在一个scrollviewer) / p>
This is how my XAML looks (I placed the uniformgrid in a scrollviewer)
<ScrollViewer Grid.Column="1" Grid.RowSpan="3">
<UniformGrid x:Name="unfiformGridSubfolders" Grid.Column="1" Grid.Row="0" Grid.RowSpan="3" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"/>
</ScrollViewer>
这是它在程序中的外观:
And this is how it looks in the program:
只需要每个checkBox有足够的空间,以便内容可以完全阅读。
I just want that every checkBox has enough space, so that the content can be fully read.
推荐答案
动态添加UI元素?你不能只是预定义你的 CheckBox
模板并添加 CheckBox.Content
而不是?如果可能,然后定义包含 CheckBox.Content
的 ObservableCollection
,如下所示:
do you have to add UI elements dynamically? can't you just predefine your CheckBox
template and add CheckBox.Content
instead? If it's possible then define an ObservableCollection
that contains your CheckBox.Content
like this:
public ObservableCollection<string> SubfolderNames { get; set; }
然后定义 ItemsControl
ItemsSource
:
<ItemsControl Grid.Row="0" x:Name="gridSubfolders" ItemsSource="{Binding SubfolderNames}" Grid.IsSharedSizeScope="True">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel></WrapPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="50" />
</Grid.ColumnDefinitions>
<Border Margin="5" BorderThickness="1" BorderBrush="Black">
<CheckBox Content="{Binding}"/>
</Border>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
这样,所有项目都具有相同的宽度,因为它们共享一个大小组, Auto
,它们也将大小为最大的 CheckBox.Content
。
This way, All Items have the same width as they share a size group, moreover because they are sized Auto
, they will also size to the largest CheckBox.Content
.
这篇关于向UniformGrid添加复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!