Bind to an ICommand on ViewModel with objects in an ItemsControl in WPF

I spent a few minutes beating my head on binding a command to a button that I had in an ItemsControl. Mainly, was creating a list of “link” buttons and wanted them to pass their binding argument to my command on the main view model.

Well, since the DataContext to the content is not the main view model but the individual data item that is in the ItemSource for the ItemsControl, you have to get creative.

Enter the RelativeSource binding. This great tool allows you to search up in the visual hierarchy and grab different data contexts. Simply put, I use the FindAncestor to search for my main UserControl instance, and then go off its DataContext to grab the command. Nice and easy.

Below is the code. Should be easy to follow:

<Window x:Class="SSI.Views.SelectorView"
                <ItemsControl Margin="0" ItemsSource="{Binding Folders}">
 <Button Content="{Binding}" Command="{Binding DataContext.FolderCommand,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type views:SelectorView}}}" CommandParameter="{Binding}"/>

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.