开发者

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.

Delete items from ListBox in WPF?

This is the code which adds items in lists.

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

        public Task(string taskname)
        {
            this.Taskname = task开发者_StackOverflow中文版name;
        }
    }

    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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜