DEV Community

Brandon Weaver
Brandon Weaver

Posted on

1

WPF ItemsControl

The ItemsControl element is a great way to implement customized representations of collections in a WPF application. Assuming that you have a view model with an observable collection, you can use the ItemsControl element to dynamically generate a button for each member of the collection.

<ItemsControl ItemsSource="{Binding MyCollection}"
              x:Name="MyCollectionControl">
    <ItemsControl.ItemsTemplate>
        <DataTemplate>
            <StackPanel>
                <Button Content="{Binding Name}"
                        Command="{Binding ElementName=MyCollectionControl, Path=DataContext.SelectMemberCommand}"
                        CommandParameter="{Binding}" />
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemsTemplate>
</ItemsControl>

The markup above will generate buttons for each member of MyCollection. The content of each button will be the Name property of the member, and the command will be the SelectMemberCommand command implemented in the view model. Since the context of each button points to a member of our observable collection, we need to reference the command by pointing to the DataContext of the parent element, which is our ItemsControl.

With an observable property in the view model we can track which member was selected and update the view accordingly.

There are endless ways in which you could use the ItemsControl to create UI elements for members of a collection; This is just a small example.

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more