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);
}
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:
I just want that every checkBox has enough space, so that the content can be fully read.
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; }
then define an ItemsControl
and bind it's ItemsSource
to your collection:
<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>
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
.