如何在WPF中将ItemsSource的索引作为CommandParameter传递

如何在WPF中将ItemsSource的索引作为CommandParameter传递,wpf,indexing,itemssource,commandparameter,Wpf,Indexing,Itemssource,Commandparameter,在WPF中: 如何将ItemsSource循环的索引作为CommandParameter传递 <ItemsControl ItemsSource="{Binding PageList}"> <ItemsControl.ItemTemplate> <DataTemplate> <Button Content="{Binding Name}" C

在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方法

谢谢大家!

简单的方法

首先,螺钉索引。他们很烂。绑定到
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);
}
//在ctor中设置
公共ObservableCollection页面列表{get;private set;}
//在setter中省略INPC内容
公共页面已选择页面{get;set;}
//下面是ICommand的Execute方法
私有void ExecuteChangePageCommand(对象参数)
{
//lol拧紧参数
var currentPage=SelectedPage;
更新所选页面或OWHATEVERLOLKTHX(当前页面);
}

您不能使用项目的
DataContext
吗?您不能在pageviewmodel中创建属性以返回父集合中的索引吗?然后你可以在你的命令参数中传递这个数字。在任何情况下,我不是在寻找一种方法来获取所选页面,我需要的是知道按下的按钮。它在列表中的位置,使用DataContext不是一个选项,因为每个项目都不知道它在列表中的位置。@MorgoZ啊,bugger。我习惯于使用列表框。至于“名单中的位置”,这似乎很奇怪。为什么ViewModel会关心项目在UI中的位置?通常的模式是“用户选择某个东西,用户处理某个东西,用户告诉VM用那个东西做某件事。”您使用索引的目的是什么?