1

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.

Ted
  • 2,525
  • 2
  • 37
  • 54

2 Answers2

2

You can send the DataContext of each item to the command via CommandParameter

 <Button Command="{Binding DeleteFoo}" CommandParameter={Binding}>Delete</Button>
user1064519
  • 2,180
  • 12
  • 13
  • Thanks very much for the help user1064519, I'd have given you the answer, but Andy beat you to it by a whole minute! – Ted Feb 28 '13 at 15:00
2

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>
Andy
  • 6,366
  • 1
  • 32
  • 37