WPF ListBox自动删除项目

5

我正在尝试设置一个列表框,用户可以通过单击要删除的每个值来删除项目。 我为我的列表框(DisplayName是项类的成员)设置了样式,以包括每个项目的按钮:

  <ListBox.ItemTemplate>
      <DataTemplate>
          <StackPanel Orientation="Horizontal">
              <TextBlock Text="{Binding DisplayName}" />
              <Button Content="[x]" />
          </StackPanel>
      </DataTemplate>
  </ListBox.ItemTemplate>

现在我遇到了一个问题,无法设置按钮来删除关联的条目。 有谁能指点一下吗? 非常感谢。


显示 ListBox 绑定并获取 - paparazzo
1个回答

7
我建议您使用ICommand,并通过命令参数传递列表框中选择的项目。
   <ListBox x:Name="MyListBoxName">
      <ListBox.ItemTemplate>
         <DataTemplate>
           <StackPanel Orientation="Horizontal">
             <TextBlock Text="{Binding DisplayName}" />
             <Button Content="[x]" 
                     Command="{Binding ElementName=MyListBoxName, Path=DataContext.DeleteItemCommand}" 
                     CommandParameter="{Binding }" />
           </StackPanel>
         </DataTemplate>
       </ListBox.ItemTemplate>
   </ListBox>

    public class YourViewModel
    {
       public ICommand DeleteItemCommand { get; set; }
       public ObservableCollection<SomeClass> ListBoxDataSource { get; set; }

       public YourViewModel()
       {
          DeleteItemCommand = new DelegateCommand<object>(DeleteItem);
       }

       private void DeleteItem(object item)
       {

       }
    }

1
接近了,但是你的绑定有点问题。ListBoxItemDataContext 将是集合中的一个项目,因此您需要使用 RelativeSourceElementName 绑定来查找 ListBox.DataContext 并获取 DeleteCommand。这比在列表中的每个项目中添加 DeleteCommand 更实用。希望你不介意,我稍微调整了你的代码示例以展示这一点 :) - Rachel
是的,你说得对。我忘记了引用层次结构。 - TMan
顺便问一下,不知道你是否还记得我,但是很久以前在我还是一个渴望学习的新手时,你回答了我的一个问题。让我告诉你,从那时起我已经走了很长一段路。 :) 你帮助我打下了基础,这对我来说付出了巨大的回报。感谢你在stackoverflow上为我和其他人提供的帮助。http://stackoverflow.com/questions/7905920/making-a-customized-schedule-in-wpf - TMan
我记得你,TMan,我们曾经进入私聊讨论过你的一篇帖子。最近我看到你有些很好的回答(我想我可能点赞了其中一两个),很高兴看到你现在对WPF已经足够熟悉,可以帮助其他新手了 :) - Rachel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接