views:

1468

answers:

2

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?

+9  A: 

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

HTH, Kent

Kent Boogaart
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
Ha! Sorry, I missed the fact that you had Source="..." instead of RelativeSource="...". See my updated answer.
Kent Boogaart
that's it, thanks.
Mark Heath
Googled SO solutions are the best solutions.
eskerber
A: 

Hi, I am still facing problem, i am getting an error: "ancestor type must be specified for relativesource in findancestor mode".

Actually I am displaying records in ItemsControl. Inside DataTemplate there is Button and I want button's click event on my ModelViewModel. So plz help.

Naresh Goradara