简体   繁体   中英

how to check if any checkbox is checked in grid,wpf

I have number of checkboxs in grid,i have to check if any check box is checked then it will print name like- 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> 
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);
}

try this :

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

you can use the checked and unchecked events attached to the check box and in these events add/remove selected/unselected items from a collection like hashtable

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

and in the code:

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

Code Behind

Have a class level: 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)
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM