5
votes

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?

2
Try searching StackOverflow. You may find loads of answers involving DataContext, VisualTreeHelper, etc.Amsakanna

2 Answers

11
votes

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

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.