jeudi 8 octobre 2020

Selecting Items in ListBox with CheckBoxes in WPF

I want to implement a Wpf Listbox with Checkboxes and to be able to Select each Item/Data entry via Index/Content property and to perform an Action.

In my MainWindow.xaml, I have:

        <ItemsControl x:Name="myListObjects" Width="330" HorizontalAlignment="Left" Margin="10,120,0,0">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <CheckBox Margin="0,0,0,0" IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}, Path=IsSelected}">
                            <TextBlock Margin="0,0,0,0" Text="{Binding}" />
                        </CheckBox>
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

In my code-behind, I have list with, e.g. 4 entries

         myListObjects.ItemsSource = new List<String>

            { "Optimize data",
               "Shred data",
               "Just remove",
               "Do nothing",
            };

Now I want something like (this code does not work from here of course)

      foreach (var item in myListObjects.Items)
                {
                    if (myListObjects.SelectedIndex == 0)
                    {
                       Do.Optimize();
                    }

                   if (myListObjects.SelectedIndex == 1)
                    {
                       Do.Shred();
                    }
                } 

Also I would like to have a possibility to Select/Unselect all entries with one click

I hope you understand my intentions. I am still having a hard time with Wpf as I'm only doing it a few days.

Many thanks in advance! Ed




Aucun commentaire:

Enregistrer un commentaire