views:

286

answers:

2

I am trying to delete items from listbox which is data binded. 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?

+4  A: 

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.

winSharp93
+2  A: 

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;
            }
        }
sanjeev40084
+1 You can remove the task directly from taskList like this `taskList.Remove(task);`. Also the else part is not required.
Veer
yeah u r rite abt that.
sanjeev40084