boomchickawah
boomchickawah

Reputation: 53

Dynamically adding controls to View from MVVM

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?

Upvotes: 3

Views: 6132

Answers (1)

Duane
Duane

Reputation: 568

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>

Upvotes: 5

Related Questions