选中所有复选框WPF

时间:2017-07-18 05:34:21

标签: c# wpf checkbox

我想通过选中" All of Above"选中复选框名称来选中所有复选框。 复选框位于列表框

<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>

返回代码

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

有人可以推荐一种方法吗?

1 个答案:

答案 0 :(得分:1)

您可以为您的&#34;以上所有&#34;处理CheckedUnchecked事件。 CheckBox这样的事情:

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

确保您的AddSource类实现INotifyPropertyChanged并在PropertyChanged属性的setter中引发IsSelected事件。