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

时间:2013-10-14 03:14:44

标签: c# xaml mvvm

我有以下用户控件

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

是因为它在项目模板中吗?

1 个答案:

答案 0 :(得分:2)

是的,这是因为DataContext的{​​{1}}是来自ItemTemplate而不是Persons

的项目

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

示例,绑定到ViewModel

DataContext
ListBox

编辑:

如果要删除单击按钮的项目,可以将按钮所属的项目作为<Button Command="{Binding Path=DataContext.DeleteItemCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}" /> 传递并在您的comman中处理,不确定您使用的是哪种类型的命令但是这样如果您使用CommandParameterRelayCommand

,则很简单
DelegateCommand