Here is one way to solve this problem. Create an ObservableCollection and set the ItemsSource for you equal to this collection. Then your button click handler can simply delete the item.
using System;
using System.Collections.ObjectModel;
using System.Windows.Controls;
namespace SilverlightApplication1
{
public partial class MainPage : UserControl
{
private ObservableCollection<string> _customers;
public MainPage()
{
InitializeComponent();
_customers = new ObservableCollection<string>() { "Bob", "Mark", "Steve" };
this.DataContext = _customers;
}
public void remove_Click(object sender, EventArgs e)
{
var button = sender as Button;
if (button == null)
return;
var name = button.DataContext as string;
if (string.IsNullOrEmpty(name))
return;
_customers.Remove(name);
}
}
}
In this example, your XAML will look like this:
<Grid x:Name="LayoutRoot">
<ListBox ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<TextBlock Text="{Binding}" />
<Button Content="Remove" Click="remove_Click" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
source
share