【问题标题】:Select all check boxes WPF选中所有复选框 WPF
【发布时间】:2017-07-18 18:02:06
【问题描述】:

我想通过选择带有“以上所有”的复选框名称来选中所有复选框。 复选框在列表框中

<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 中处理所有事情,因为你有 Binding。

标签: c# wpf checkbox


【解决方案1】:

您可以为“以上所有”CheckBox 处理 CheckedUnchecked 事件,如下所示:

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 属性的设置器中引发PropertyChanged 事件。

【讨论】:

  • 是的,确切的原因是我没有实现 INotifyPropertyChanged。现在它可以工作了..谢谢
猜你喜欢
  • 2018-08-03
  • 2015-08-25
  • 2018-10-19
  • 2016-01-29
  • 2010-10-19
  • 2010-10-27
  • 1970-01-01
相关资源
最近更新 更多