如何检查网格中是否有复选框被选中,wpf

本文关键字:复选框 wpf 是否 检查 网格 何检查 | 更新日期: 2023-09-27 18:26:54

我在网格中有很多复选框,我必须检查是否选中了任何复选框,然后它将打印名称,如-MsgBox("CheckboxName")。

<Grid Height="179" Width="290" Name="Checksum_Collection" >
        <CheckBox Content="Alder32" Height="20" Name="Alder32CheckBox" />
        <CheckBox Content="BsdChecksum" Height="20" Name="BsdChecksumCheckBox"/> 
        <CheckBox Content="CRC16" Height="20" Name="CRC16CheckBox"/>
        <CheckBox Content="Damm" Height="20" Name="DammCheckBox"/>
        <CheckBox Content="Fletcher" Height="20" Name="FletcherCheckBox" />
        <CheckBox Content="LRC" Height="20" Name="LRCCheckBox"  />
        <CheckBox Content="Luhn" Height="20" Name="LuhnCheckBox"/>
        <CheckBox Content="MD5 Hash" Height="20" Name="MD5CheckBox"/>
</Grid> 

如何检查网格中是否有复选框被选中,wpf

using System.Linq;
foreach (var checkBox in Checksum_Collection.Children
    .OfType<CheckBox>()
    .Where(cb => (bool)cb.IsChecked))
{
    var name = checkBox.Name;
    Trace.TraceInformation("{0} is checked", name);
}

试试这个:

foreach(var child in Checksum_Collection.Children)
{
    if(child.getType() == typeof(CheckBox))
    {
        if(child.IsChecked)
            MsgBox ("CheckboxName");    // or do whatever u want
    }
}

您可以使用附加到复选框的已检查和未检查事件,并在这些事件中添加/删除像哈希表这样的集合中的选定/未选定项目

<CheckBox Content="Item 1" Checked="CheckBox_Checked"    Unchecked="CheckBox_Unchecked"/>

并且在代码中:

List<string> SelectedItems = new List<string>();
    private void CheckBox_Checked(object sender, RoutedEventArgs e)
    {
        SelectedItems.Add((e.OriginalSource as CheckBox).Name.ToString());
    }
    private void CheckBox_UnChecked(object sender, RoutedEventArgs e)
    {
        SelectedItems.Remove((e.OriginalSource as CheckBox).Name.ToString());
    }

XAML

<dxe:CheckEdit IsChecked="{Binding RowData.Row.IsSelected}" Checked="CheckEdit_Checked" 
 Unchecked="CheckEdit_Checked"  HorizontalAlignment="Center" VerticalAlignment="Center"/>

背后的代码

具有类级别:isAnyChecked=0;

private void CheckEdit_Checked(object sender, RoutedEventArgs e)
{
if (e.RoutedEvent.Name == "Checked")
{
    isAnyChecked += 1;
}
else if(e.RoutedEvent.Name =="Unchecked")
{
    isAnyChecked -= 1;
    if(isAnyChecked == 0)
}
}