我有以下用户控件
<ListBox ItemsSource="{Binding Persons}"
SelectedItem="{Binding SelectedPerson}"
VerticalAlignment="Top" Width="166" >
<ListBox.Template>
<ControlTemplate>
<StackPanel >
<ItemsPresenter/>
<Button Content="Add" Background="Transparent" Command="{Binding NewItemCommand}"/>
</StackPanel>
</ControlTemplate>
</ListBox.Template>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button Height="16" Width="16" Background="Transparent" Command="{Binding DeleteItemCommand}">
<Image Source="images/delete-icon.png" />
</Button>
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我有一个带有两个命令的视图模型,您可以在上面看到的第一个命令NewItemCommand
工作正常,第二个命令DeleteItemCommand
如何不起作用。
是因为它在项模板中吗?
是的,这是因为ItemTemplate
的DataContext
是来自Persons
的项目,而不是ViewModel
要绑定每个项目上的DeleteItemCommand
,您需要绑定回保存命令的ViewModel
例如,绑定到ListBox
的DataContext
<Button Command="{Binding Path=DataContext.DeleteItemCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}" />
编辑:
如果要删除单击按钮的项目,可以将按钮所属的项目作为CommandParameter
传递,并在您的 comman 中处理它,不确定您使用的命令类型,但如果您使用的是RelayCommand
或DelegateCommand
,这很简单
<Button Command="{Binding Path=DataContext.DeleteItemCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}"
CommandParameter="{Binding}" />
public MainWindow()
{
InitializeComponent();
DeleteItemCommand = new RelayCommand(person => DeletePerson(person as Person));
}
private void DeletePerson(Person person)
{
Collection.Remove(person);
}