带有自删除项目的 WPF ListBox

use*_*850 4 wpf listbox button

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

  <ListBox.ItemTemplate>
      <DataTemplate>
          <StackPanel Orientation="Horizontal">
              <TextBlock Text="{Binding DisplayName}" />
              <Button Content="[x]" />
          </StackPanel>
      </DataTemplate>
  </ListBox.ItemTemplate>
Run Code Online (Sandbox Code Playgroud)

现在我在尝试设置按钮以删除相关条目时遇到问题。有人可以指点一下吗?先感谢您。

TMa*_*Man 6

我建议您使用 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>
Run Code Online (Sandbox Code Playgroud)
    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)
       {

       }
    }
Run Code Online (Sandbox Code Playgroud)