在這種情況下,最好是您的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