Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding controls to View from MVVM

Tags:

mvvm

wpf

In WPF, I am using the MVVM model.

I have a View with a Dockpanel and I want to add dynamically StackPanels with a Label and TextBox for all Harddisks found over the Binding.

Therefore my XAML looks like:

<DockPanel Grid.Row="1" HorizontalAlignment="Stretch" Margin="5">
       <ItemsControl ItemsSource="{Binding Harddisks}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel DockPanel.Dock="Right" HorizontalAlignment="Right" Margin="2.5,0,0,0">
                        <Label Content="{Binding Path=Label}" />
                        <TextBox Text="{Binding Path=GB_Free}" Width="100" IsReadOnly="True"/>
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

It should be four Labels and TextBoxes, but only the first Label and TextBox are shown. Why?

like image 605
boomchickawah Avatar asked Dec 07 '25 08:12

boomchickawah


1 Answers

Your items in your ItemsControl are not actually direct children of the DockPanel. You need to change the ItemsControl to specify that the DockPanel is the Panel. The following will cause the ItemsControl to create a DockPanel and place all the items inside it (rather than the StackPanel that ItemsControl uses by default).

More Info: MSDN: ItemsControl.ItemsPanel Property

   <ItemsControl ItemsSource="{Binding Harddisks}">
        <ItemsControl.ItemsPanel>
            <DockPanel Grid.Row="1" HorizontalAlignment="Stretch" Margin="5" />
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel DockPanel.Dock="Right" HorizontalAlignment="Right" Margin="2.5,0,0,0">
                    <Label Content="{Binding Path=Label}" />
                    <TextBox Text="{Binding Path=GB_Free}" Width="100" IsReadOnly="True"/>
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
like image 187
Duane Avatar answered Dec 09 '25 03:12

Duane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!