27

I have an ItemsControl whose for the ItemTemplate DataTemplate contains a Button. I want the Command on the button to bind to a Command on the DataContext of the ItemsControl, not the ItemTemplate. I think the solution has to do with using RelativeSource, but my attempts so far have failed:

<ItemsControl ItemsSource="{Binding Games}">        
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Command="{Binding Path=GameSelectedCommand, Source={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" 
                    CommandParameter="{Binding}" 
                    Style="{StaticResource MenuButtonStyle}" 
                    Content="{Binding Name}"/>    
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

How can I get the Button to bind to the GameSelectedCommand of the ItemsControl's DataContext object?

Mark Heath
  • 48,273
  • 29
  • 137
  • 194

1 Answers1

46

You're setting the source of the binding to the ItemsControl itself. Therefore, you'll need to dereference the DataContext of the ItemsControl:

Command="{Binding DataContext.GameSelectedCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}"

How would you have known this? Take a look at your debug output window when running the app. You'll see a message along the lines of "Cannot resolve property 'GameSelectedCommand' on type 'ItemsControl'".

Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
  • 1
    thanks for the answer, but I did actually try this. I got the following DataBinding error: System.Windows.Data Error: 39 : BindingExpression path error: 'DataContext' property not found on 'object' ''RelativeSource' (HashCode=50668565)'. BindingExpression:Path=DataContext.GameSelectedCommand; DataItem='RelativeSource' (HashCode=50668565); target element is 'Button' (Name=''); target property is 'Command' (type 'ICommand') I'm not sure its actually finding the ItemsControl itself – Mark Heath Oct 02 '09 at 20:08
  • 3
    Ha! Sorry, I missed the fact that you had Source="..." instead of RelativeSource="...". See my updated answer. – Kent Boogaart Oct 02 '09 at 20:16
  • 1
    Googled SO solutions are the best solutions. – Erik Kerber Jul 01 '10 at 20:45
  • 1
    ahh! i always succeed in forgetting this every time! – Simon_Weaver Dec 15 '10 at 08:31
  • don't forget to explicitly put `DataContext.` in the binding path. used to make that mistake all the time too :) – Simon_Weaver Jun 16 '12 at 04:41