views:

394

answers:

2

Hello,

The functionality I want is to have a remove button beside each item of a listbox so when the user clicks it, that specific item gets removed from the list.

I am thinking about putting it in the data template but how would I wire up an even to that?

Thanks, Shawn Mclean

A: 

Bind ItemsSource of your ListBox to ObservableCollection. Put a delete button into data template. Click event handler for the button can be something like this:

private void Button_Click(object sender, RoutedEventArgs e)
{
    var button = sender as Button;
    if (button != null)
    {
        var yourObject = button.DataContext as YourObject;
        if (yourObject != null)
        {
            YourObjectsObservableCollection.Remove(yourObject); 
        }
    }
}

So you can retrieve the object which is bound to ListBoxItem from buttons DataContext.

bniwredyc
+1  A: 

Here is one way to approach this issue. Create an ObservableCollection and set you ItemsSource equal to that Collection. Then your Button click handler can just remove 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 sample your XAML would 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>
bendewey