3

在 WPF 中:如何将 ItemsSource 循环的索引作为 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>

所以,我想要的是将按下的按钮编号传递给 Command 方法。

谢谢!

4

1 回答 1

-1

简单的方法来做到这一点。

一是螺丝指标。他们很烂。绑定到SelectedItem

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

现在,您不必尝试将索引传递给参数,因为所选页面已经在您的 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);
}
于 2014-12-17T15:25:34.773 回答