在这种情况下,最好是您的ViewModel具有该命令并需要一个参数。这样,你会传递用户试图修改的项目。所以,如果你有一个ItemsControl
:
<ItemsControl ItemsSource="{Binding MyItems}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Name, StringFormat=Push {0}}"
Command="{Binding DataContext.ItemPushedCommand, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"
CommandParameter="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
在您的视图模型,你需要定义你的命令,像这样(我使用的是DelegateCommand从prism,你可以使用任何命令你是舒服):
private readonly DelegateCommand<Model> itemPushedCommand;
public ICommand ItemPushedCommand { get { return itemPushedCommand; } }
public MyViewModel()
{
itemPushedCommand = new DelegateCommand<Model>(OnItemPushed);
}
private void OnItemPushed(Model item)
{
// your item has been pushed!
}
和内部OnItemPushed我可以调用项目的例程。谢谢你的回答,这是我一直在寻找的。 – Andrei