WPF: Expandable list of item groups

71 views Asked by At

I am new to WPF and am wondering how can I create a view which contains an expandable number of item groups. In the group of items I want to place a Label and a RadComboBox. I want to have a button (+), on click of which a new group of items appears in the list.

So imagine we start with an empty view and a (+) button. By clicking (+) a label with a combobox appear. Then by clicking (+) again another label with a combobox appears. And I want this list to be able to fit as many groups as I want. The content of the label and the combobox will be determined by the DataContext of the parent list.

Later I want to also add a (-) button that will remove the selected group, but I think I can figure it out myself once I know which elements to use for this.

Does someone know how can I do this? Which element can fit these groups stacked horizontally and how can I place a label and a combo box in a single "group"? I am mainly concerned about the XAML code and the logic behind the (+) button.

1

There are 1 answers

1
Étienne Laneville On BEST ANSWER

You can do this using an ItemsControl. You would bind the ItemsSource to an ObservableCollection in your View Model.

Here's a simple example (inspired by this tutorial) that demonstrates how to build the template to display each group:

<ItemsControl Height="30">
            
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
            
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Label Content="{Binding}" />
                <ComboBox Width="50" />
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>

    <system:String>Item #1</system:String>
    <system:String>Item #2</system:String>
    <system:String>Item #3</system:String>
    <system:String>Item #4</system:String>
    <system:String>Item #5</system:String>
            
</ItemsControl>

The ItemsPanel defines the panel that controls the layout of groups. Here I used a StackPanel with Orientation set to Horizontal. ItemTemplate sets the DataTemplate used to display each group. Here I used a Label and a ComboBox. The DataContext in the ItemTemplate will be an item from the ObservableCollection you set as your ItemsSource.

As far as the (+) button, you can use a Button that will add an element to your ObservableCollection. You should create a Command for this on your ViewModel and bind your Button's Command property to it.