我有以下用户控件
<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
如何不起作用。
是因为它在项目模板中吗?
答案 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中处理,不确定您使用的是哪种类型的命令但是这样如果您使用CommandParameter
或RelayCommand
DelegateCommand