如果命令绑定位于列表框的项模板内,则命令绑定不起作用

本文关键字:命令 绑定 不起作用 于列表 定位 如果 列表 | 更新日期: 2023-09-27 18:35:16

我有以下用户控件

<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如何不起作用。

是因为它在项模板中吗?

如果命令绑定位于列表框的项模板内,则命令绑定不起作用

是的,这是因为ItemTemplateDataContext是来自Persons的项目,而不是ViewModel

要绑定每个项目上的DeleteItemCommand,您需要绑定回保存命令的ViewModel

例如,绑定到ListBoxDataContext

<Button Command="{Binding Path=DataContext.DeleteItemCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}" />

编辑:

如果要删除单击按钮的项目,可以将按钮所属的项目作为CommandParameter传递,并在您的 comman 中处理它,不确定您使用的命令类型,但如果您使用的是RelayCommandDelegateCommand,这很简单

 <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);
}