WPF ListBox with self-removing items

穿精又带淫゛_ 提交于 2019-12-07 12:46:20

问题


I am trying to set up a listbox where users can remove items by clicking on each value they want to remove. I set up the style for my listbox (DisplayName is a member of the item class) in orderto include a button for each item:

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

Now I am having trouble trying to set the button to delete the associated entry. Can anybody point a way? Thank you in advance.


回答1:


I'd recommend you use an ICommand and pass the selected item of the listbox through a command parameter.

   <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)
       {

       }
    }


来源:https://stackoverflow.com/questions/22770440/wpf-listbox-with-self-removing-items

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!