How to pass index of an ItemsSource as CommandParameter in WPF

2.2k Views Asked by At

In WPF: How can i pass the index of a ItemsSource loop as a CommandParameter?

<ItemsControl ItemsSource="{Binding PageList}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button 
                Content="{Binding Name}"
                Command="{Binding DataContext.ChangePageCommand, ElementName=Window}"
                CommandParameter="INDEX OF ACTUAL ITEM AT ITEMSSOURCE GOES HERE" />
        </DataTemplate>
    </ItemsControl.ItemTemplate> 
</ItemsControl>

So, what i want is to pass the pushed button number to the Command method.

Thank you!

1

There are 1 best solutions below

2
On

Simple way to do it.

First, screw indexes. They suck. Bind to SelectedItem

<ItemsControl ItemsSource="{Binding PageList}" SelectedItem="{Binding SelectedPage}">

Now, you don't have to try and pass the index into the parameter, because the selected page is already in your ViewModel.

// set in the ctor
public ObservableCollection<Page> PageList {get;private set;}
// Omitting INPC stuff in the setter
public Page SelectedPage {get;set;}

// Here's the Execute method of the ICommand
private void ExecuteChangePageCommand(object parameter)
{
   // lol screw the parameter
   var currentPage = SelectedPage;
   UpdateSelectedPageOrDoWhateverLolKthx(currentPage);
}