Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all check boxes WPF

Tags:

c#

checkbox

wpf

I want to make all check boxes selected by selecting check box names with "All of Above". the checkboxes are in a List box

<ListBox SelectionMode="Multiple" 
         BorderThickness="0" 
         ItemsSource="{Binding QuestionThreeSelection}" 
         SelectedItem="{Binding QuestionThreeSelection}" 
         Name="listBoxList" 
         SelectionChanged="listBoxList_SelectionChanged">
    <ListBox.InputBindings>
        <KeyBinding Command="ApplicationCommands.SelectAll"
                    Modifiers="Ctrl"
                    Key="A" />
    </ListBox.InputBindings>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox Checked="CheckBox_Checked_1"   
                      Content="{Binding SourceName}" 
                      IsChecked="{Binding Path=IsSelected,  Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

back Code

private void CheckBox_Checked_1(object sender, RoutedEventArgs e)
{          
    var oo = listBoxList;
    CheckBox cb = (CheckBox)sender;
    //var w=e;

    IEnumerable<AddSource> listallityem = ((IEnumerable<AddSource>)listBoxList.Items.SourceCollection).Where(r => r.IsSelected == false);
    //IEnumerable<AddSource> listallityem1 = ((IEnumerable<AddSource>)listBoxList.Items.SourceCollection);

    AddSource vv = cb.DataContext as AddSource;
    if ((bool) cb.IsChecked)
    {

    }

    if (vv.SourceName== "All of the above")
    {
        r = listBoxList.ItemsSource;

        foreach (AddSource item in wer)
        {
            item.IsSelected = true; // false in case of unselect
        }
    }
}

Can someone suggest a method?

like image 834
Shan Peiris Avatar asked Oct 17 '22 09:10

Shan Peiris


1 Answers

You could handle the Checked and Unchecked event for your "All of Above" CheckBox something like this:

private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
    SelectAll(true);
}

private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
{
    SelectAll(false);
}

private void SelectAll(bool select)
{
    var all = listBoxList.ItemsSource as IEnumerable<AddSource>;
    if (all != null)
    {
        foreach (var source in all)
            source.IsSelected = select;
    }
}

Make sure that your AddSource class implements the INotifyPropertyChanged and raise the PropertyChanged event in the setter of the IsSelected property.

like image 174
mm8 Avatar answered Oct 21 '22 00:10

mm8