Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silverlight: Events in datatemplate for listboxes

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

like image 521
Shawn Mclean Avatar asked Dec 10 '25 22:12

Shawn Mclean


2 Answers

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>
like image 197
bendewey Avatar answered Dec 12 '25 18:12

bendewey


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.

like image 42
bniwredyc Avatar answered Dec 12 '25 20:12

bniwredyc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!