admiri
admiri

Reputation: 528

Remove current clicked ListBox item (ObservableCollcetion)

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?

Upvotes: 0

Views: 54

Answers (2)

mm8
mm8

Reputation: 169170

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

Upvotes: 1

lionthefox
lionthefox

Reputation: 439

This should do the trick:

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

Upvotes: 0

Related Questions