问题
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