Reputation: 329
I want to find how much check box is checked by code :
<Grid Width="440" >
<ListBox Name="listBoxZone" ItemsSource="{Binding TheList}" Background="White" Margin="0,120,2,131">
<ListBox.ItemTemplate>
<HierarchicalDataTemplate>
<CheckBox Name="CheckBoxZone" Content="{Binding StatusName}" Tag="{Binding StatusId}" Margin="0,5,0,0" VerticalAlignment ="Top" />
</HierarchicalDataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
Here is my code where i want to find how much check box is checked ?
for (int i = 0; i < listBoxZone.Items.Count; i++)
{
if (CheckBoxZone.IsChecked == true )
{
}
}
Upvotes: 0
Views: 726
Reputation: 48558
Use OfType
Method of LINQ
int result =
listBoxZone.Items.OfType<CheckBox>().Count(i => i.IsChecked == true);
I used OfType
instead of Cast
because OfType
will work even if there a single checkbox item or all items are checkboxes.
In case of Cast
it will give error if even a single item is not checkbox.
Upvotes: 0
Reputation: 128061
You could add an IsChecked
property of type Nullable<bool>
(could be written as bool?
) to your data item class and two-way bind the CheckBox.IsChecked property:
<CheckBox Name="CheckBoxZone" IsChecked={Binding IsChecked, Mode=TwoWay} ... />
Now you can simple iterate over all items and check their IsChecked
state:
int numChecked = 0;
foreach (MyItem item in listBoxZone.Items)
{
if ((bool)item.IsChecked) // cast Nullable<bool> to bool
{
numChecked++;
}
}
or with Linq:
int numChecked =
itemsControl.Items.Cast<MyItem>().Count(i => (bool)i.IsChecked);
And just a note: why do you use HierarchicalDataTemplate in a ListBox, where DataTemplate would be sufficient?
Upvotes: 3