Silverlight: events in datatemplate for lists

I want to have a delete button next to each item in the list, so when a user clicks on it, that particular item is removed from the list.

I'm thinking of putting it in a data template, but how would I connect it to this?

Thanks, Shawn Mclean

+3
source share
2 answers

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>
+2
source

ListBox ObservableCollection. . Click :

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); 
        }
    }
}

, , ListBoxItem, DataContext.

+1

Source: https://habr.com/ru/post/1726516/


All Articles