Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete items from ListBox in WPF?

Tags:

wpf

listbox

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?

like image 585
sanjeev40084 Avatar asked May 24 '10 15:05

sanjeev40084


1 Answers

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;
            }
        }
like image 68
sanjeev40084 Avatar answered Oct 04 '22 00:10

sanjeev40084