I have a ListBox containing an ObservableCollection and a corresponding Button. I want to remove a ListBoxItem on corresponding button click.

ListBox

I have added the following c# code:

public ObservableCollection<DailySession> dailySession;

...

 while (reader.Read())
        {

            dailySession = new ObservableCollection<DailySession>()
            {
                new DailySession { Name =reader.GetString(0) }

            };

            DailySessions.Items.Add(dailySession);
        }

In order to remove the ListBoxItem I have implemented this code:

 private void btnClear_Click(object sender, RoutedEventArgs e)
    {
       //DailySessions is the Listbox name, btnClear is button name

        DailySessions.Items.Remove(DailySessions.SelectedItem);// returns null
        //DailySessions.Items.RemoveAt(DailySessions.SelectedIndex);// returns -1

    }

I have failed to get the index of ListBoxItem I have clicked.

Is there any other way to remove selected item from ListBox?

2 Answers

1
mm8 On Best Solutions

You could cast the DataContext of the clicked Button:

private void btnClear_Click(object sender, RoutedEventArgs e)
{
    Button clickedButton = (Button)sender;
    DailySessions.Items.Remove(clickedButton.DataContext as DailySession);
}
0
lionthefox On

This should do the trick:

private void btnClear_Click(object sender, RoutedEventArgs e)
{    
  DailySessions.Items.RemoveAt(DailySessions.Items.IndexOf(DailySessions.SelectedItem));
}