3

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!

MorgoZ
  • 2,012
  • 5
  • 27
  • 54

1 Answers1

-1

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);
}
  • 2
    In any case, i´m not looking for a way to get the selected page, what i need is to know the button that was pushed. Its position at the list, and using DataContext is not an option since each item doesn´t know its position in the list. – MorgoZ Dec 17 '14 at 15:46
  • @MorgoZ ah bugger. I'm used to using a ListBox. As for "position in the list" that seems very odd. Why would the ViewModel care about the position of an item in the UI? The normal pattern is "user selects something, user works on something, user tells VM to do something with that something." What are you using the index for? –  Dec 17 '14 at 15:50