Bind to ItemsControl's DataContext from inside an ItemTemplate
Asked Answered
H

1

28

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?

Hitlerism answered 2/10, 2009 at 19:59 Comment(0)
T
47

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'".

Thurnau answered 2/10, 2009 at 20:5 Comment(5)
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 itselfHitlerism
Ha! Sorry, I missed the fact that you had Source="..." instead of RelativeSource="...". See my updated answer.Thurnau
Googled SO solutions are the best solutions.Pairs
ahh! i always succeed in forgetting this every time!Drews
don't forget to explicitly put DataContext. in the binding path. used to make that mistake all the time too :)Drews

© 2022 - 2024 — McMap. All rights reserved.