K. Fenster
K. Fenster

Reputation: 91

Create Multiple Items Using ItemsControl

I am a novice when it comes to WPF so I don't even know if what I am trying to do is possible. I have been reading about ItemsControl to create numerous instances of an item. All of the examples I have seen, only allow you to create X number of items for one "type" like the below example:

ItemsControl ItemsSource="{Binding MyCollection}">
    <ItemsControl.ItemTemplate>
       <DataTemplate>
           <Button Content="{Binding }" />
       </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

which creates a button for every item in the ItemSource.

I want to be able to create items of various types like a TextBox, Button, and ComboBox using ItemsControl any time I click a button. So when I click samp_Btn1 I want a new TextBox and button to appear beneath the one's I already have displayed.

I tried:

 ItemsControl>
    <ItemsControl.ItemTemplate>
       <DataTemplate>
           <Button Name="test_Btn"
              Width="50"
              Height="50"/>
           <TextBox Name="test_TextBox" Width="50" Height="50" />
       </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

and then a function that just created a new ItemControl

        private void createNewItem()
    {
        ItemsControl test = new ItemsControl();
    }

but I keep getting an error saying the PropertyVisual Tree is set more than once. Is this the right way to go about things or do I need to create an ItemControl for the TextBox and Button separately?

Upvotes: 0

Views: 1826

Answers (1)

Kamil Solecki
Kamil Solecki

Reputation: 1117

As @NSGaga and @Clemens pointed, you should wrap your controls in a container - for example a grid.

<ItemsControl>
<ItemsControl.ItemTemplate>
   <DataTemplate>
       <Grid>
           <Button Name="test_Btn" Width="50" Height="50"/>
           <TextBox Name="test_TextBox" Width="50" Height="50" />
       </Grid>
   </DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

Remember that it does not refer only to ItemsControl. Try putting, ex. two grids directly as a MainWindow Content. You will get:

The property "Content" can only be set twice.

These controls are not designed to hold a collection of children.

The elements need to have some kind of a reference frame. Thats what you use grid for - you physically position them, by giving them positions relative to the Grid.

Also, if it's some kind of elaborate design with extra functionality that you are trying to create within ItemsControl, you might consider looking into UserControl.

For that, here is a link to get you started.

Upvotes: 1

Related Questions