选中所有的复选框 WPF

5
我希望通过选择“所有选项”复选框名称来选择所有复选框,这些复选框位于列表框中。
<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
        }
    }
}

有人能提供一种方法吗?

由于您拥有绑定,因此您可以在ViewModel中处理所有内容。 - Rekshino
1个回答

3
您可以通过以下方式处理“所有上述”复选框的Checked和Unchecked事件:
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 接口,并在 IsSelected 属性的 setter 中触发 PropertyChanged 事件。


是的,确切的原因是我没有实现 INotifyPropertyChanged。现在它可以工作了。谢谢。 - Shan Peiris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接