Search code examples
c#wpflistitemtemplate

How to remove checked items from a listbox in WPF?


I have been working on a checklist application, and I am using a ListBox to display the data. I am using arrays to populate the ListBox based on what button the user presses. (I don't know if that's best practice but it works for now.) Once the user has completed the steps, he can remove the items with this command:

private void SendSelected()
{
    while (lstToDo.SelectedItems.Count > 0)
    {
        lstToDo.Items.Remove(lstToDo.SelectedItem);
    }
}

The problem is that today I have learned how to add CheckBoxes to my ItemTemplate with the xaml below:

<ListBox.ItemTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal">
            <CheckBox Padding="10">                            
                <CheckBox.LayoutTransform>
                    <ScaleTransform ScaleX="1" ScaleY="1" />
                </CheckBox.LayoutTransform>
            </CheckBox>
            <TextBlock Text="{Binding}"/>
        </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

Now the remove button still works... however I would like to adjust it so that it removes the checked items instead of selected items. In winforms, I used to do it like this:

while (lstToDo.CheckedItems.Count > 0)
{
    lstToDo.Items.Remove(lstToDo.CheckedItems[0]);
}  

But in WPF, obviously this method doesn't work, and I am just not sure why.


Solution

  • you can bind the checkbox to the IsSelected property of the ListBoxItem

    <DataTemplate>
        <CheckBox Content="{Binding .}" IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}, Path=IsSelected" />
    </DataTemplate>