2014-03-31 28 views
3

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

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

现在我有麻烦试图设置按钮删除相关条目。 有人可以指路吗? 预先感谢您。

+0

显示列表框结合,并得到 – Paparazzi

回答

3

我建议您使用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

关闭,但您的绑定是有点过。 “ListBoxItem”的'DataContext'将是集合中的一个项目,因此您需要使用'RelativeSource'或'ElementName'绑定来查找'ListBox.DataContext'并获取DeleteCommand。这比为列表中的每个项目添加“DeleteCommand”更实用。我希望你不介意,但我正在调整你的代码示例来显示这个:) – Rachel

+0

是的你的权利。我忘记了参考层次。 – TMan

+0

顺便说一下,如果你还记得我,但你很早以前回答我的问题时,我仍然是绝望的新秀,希望学习。让我告诉你我从那以后就采用了LONNNGG方式。 :)你有助于为我奠定基础,并为我付出了很大的时间。感谢您的帮助,并帮助其他人解决堆栈溢出问题。 http://stackoverflow.com/questions/7905920/making-a-customized-schedule-in-wpf – TMan