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"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
              xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
              mc:Ignorable="d"
             xmlns:views="clr-namespace:SSI.I8N.LanguagePackEditor.Views"
        Title="SSI">
                <ItemsControl Margin="0" ItemsSource="{Binding Folders}">
<ItemsControl.ItemTemplate>
<DataTemplate>
 <Button Content="{Binding}" Command="{Binding DataContext.FolderCommand,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type views:SelectorView}}}" CommandParameter="{Binding}"/>
                </DataTemplate>
           </ItemsControl.ItemTemplate>
</ItemsControl></Window>

Happy coding!

Leave a Reply

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