Tobias Moe Thorstensen
Tobias Moe Thorstensen

Reputation: 8981

Getting CurrentItem within a nested ItemsControl

I have an itemscontrol, with a item template. Inside this item template another itemscontrol exists. The latter ItemsControl has a button in its template, the command bound to this template needs to get the "parent" itemscontrol current item.

The structure looks something like this:

<ItemsControl x:Name="outerItemsControl" ItemsSource={Binding MyCollection}>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <ItemsControl ItemsSource={Binding MySecondCollection}>
                <ItemTemplate>
                    <DataTemplate>
                        <Button Command="{Binding MyFantasticCommand}"
                                CommandParameter="{Binding ????}"/>
                    </DataTemplate>
                </ItemTemplate>
            </ItemsControl>
        </DataTemplate>
    <ItemControl.ItemTemplate>
</ItemsControl> 

What should I replace the {Binding ????} with to get hold of the current item in MyCollection?

I've tried with both:

Binding ., ElementName=outerItemsControl

and

Binding Path="." RelativeSource="{RelativeSource AncestorType={x:Type ItemsControl}, AncestorLevel=2}

EDIT

Usually when we need to access the "current item" in an items control we do the following:

<ItemsControl x:Name="outerItemsControl" ItemsSource={Binding MyCollection}>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
               <Button Command="{Binding MyCommand}" CommandParameter="{Binding .}"/>
            </DataTemplate>
        <ItemControl.ItemTemplate>
    </ItemsControl> 

I want to do the same as this example, but access the parent's "current" item from the child itemscontrol.

Upvotes: 0

Views: 453

Answers (1)

Clemens
Clemens

Reputation: 128061

It seems you want to access the object with the MySecondCollection property from the inner DataTemplate.

This should work:

CommandParameter="{Binding DataContext,
    RelativeSource={RelativeSource AncestorType=ContentPresenter, AncestorLevel=2}}"

Upvotes: 1

Related Questions