Reputation: 528
I have a ListBox
containing an ObservableCollection
and a corresponding Button
.
I want to remove a ListBoxItem
on corresponding button click.
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
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
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