3

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?

1
  • You can look at what is happening by using a tool like snoop to inspect the elements at runtime. I find it invaluable when something is not being rendered as you expect. snoopwpf.codeplex.com Commented Jan 29, 2013 at 17:38

1 Answer 1

5

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Ok it seems to work and all Labels and Textboxes are shown. But there is a strange Effect. I have now 3 Labels and TextBoxes at the left side and the last Label and TextBox at the Right Side.What is the reason for this? Ok I solved it by changing the Horizontal Alignment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.