WPF列表框具有自我删除的项目 [英] WPF ListBox with self-removing items

查看:159
本文介绍了WPF列表框具有自我删除的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立一个列表框,用户可以通过点击他们想要删除的每个值删除项目。
我设置了风格我列表框(显示名称是物品类的成员)的orderto包括每个项目的按钮:

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.

推荐答案

我建议你使用一个ICommand并通过命令参数传递列表框的选择项。

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

       }
    }

这篇关于WPF列表框具有自我删除的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆