sanjeev40084
sanjeev40084

Reputation: 9617

Delete items from ListBox in WPF?

I am trying to delete items from listbox which is data bound. Here is the screenshot how listbox look like.

alt text

This is the code which adds items in lists.

    public class Task
    {
        public string Taskname { get; set; }

        public Task(string taskname)
        {
            this.Taskname = taskname;
        }
    }

    public void GetTask()
    {
        taskList = new List<Task>
                           {
                               new Task("Task1"),
                               new Task("Task2"),
                               new Task("Task3"),
                               new Task("Task4")
                           };

        lstBxTask.ItemsSource = taskList;
    }

This is the Xaml code,

 <ListBox x:Name="lstBxTask" Style="{StaticResource ListBoxItems}" >
        <ListBox.ItemTemplate>                
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Taskname}"  Style="{StaticResource TextInListBox}"/>
                    <Button Name="btnDelete" Style="{StaticResource DeleteButton}" Click="btnDelete_Click">
                    </Button>                        
                </StackPanel>                    
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

Whenever item in a listbox is selected, delete (x) button is displayed. When clicked it should delete that item from the listbox. Can anyone tell me how can I do this?

Upvotes: 5

Views: 17529

Answers (2)

sanjeev40084
sanjeev40084

Reputation: 9617

ok this is what i did. Observablecollection worked like charm.

private ObservableCollection<Task> taskList;

public void GetTask()
        {
            taskList = new ObservableCollection<Task>
                               {
                                   new Task("Task1"),
                                   new Task("Task2"),
                                   new Task("Task3"),
                                   new Task("Task4")
                               };

            lstBxTask.ItemsSource = taskList;
        }

 private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            if (button != null)
            {
                var task = button.DataContext as Task;

                ((ObservableCollection<Task>) lstBxTask.ItemsSource).Remove(task);
            }
            else
            {
                return;
            }
        }

Upvotes: 11

Matthias
Matthias

Reputation: 12259

Try using an ObservableCollection<T> instead of a simple List<T>.

The ObservableCollection<T> will notify the WPF-binding-system whenever its content has changed. Therefore, you will only have to remove the item from the list and the UI will be updated.

Upvotes: 7

Related Questions