Search code examples
wpflistviewmvvmdatatemplateheadereditemscontrol

Get reference to an item in a HeaderedItemsControl


XAML:

<HeaderedItemsControl ItemsSource="{Binding FooCollection}">
<HeaderedItemsControl.ItemTemplate>
    <DataTemplate>
        <StackPanel>
            <TextBlock Text={Binding foo}/>
            <Button Command="{Binding DeleteFoo}">Delete</Button>
        </StackPanel>
    </DataTemplate>
</HeaderedItemsControl.ItemTemplate>

Given this XAML, how can I get a reference to the item clicked in FooCollection, in the DeleteFoo command & method, in the ViewModel? Normally in a DataGrid etc, it would just be the SelectedItem bound in your ViewModel, but annoyingly the HeaderedItemsControl doesn't have this option.

Is there another way to pass a reference to the item, or its index position in FooCollection via CommandArguments for example?

I realise that the ListView is a similar control, that has a selectedItem equivalent, however I've got a nicely formatted HeaderedItemsControl set up (with a title header) so I'd prefer to not have to ditch that if possible.

Thanks very much in advance for any help.


Solution

  • I'll put it as an answer anyway.. ItemsControls set the DataContext of the ListItem to the object that they represent so you can probably get the reference to the clicked item using

    <HeaderedItemsControl ItemsSource="{Binding FooCollection}">
    <HeaderedItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text={Binding foo}/>
                <Button Command="{Binding DeleteFoo}" CommandParameter={Binding}>Delete</Button>
            </StackPanel>
        </DataTemplate>
    </HeaderedItemsControl.ItemTemplate>