Answer the question
In order to leave comments, you need to log in
How to tick all ListView items in C#?
There is a ListView with checkboxes, for example, 1000 items in size, you need to tick all the checkboxes with one keystroke. Google only suggests iterating over and setting the checked property to true on each element at a time. This naturally takes a long time with a large number of elements.
Answer the question
In order to leave comments, you need to log in
There are different options, here is one of them.
Let's say we have a ListBox like this:
<ListBox ItemsSource="{Binding ItemCollection}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding isChecked, Mode="TwoWay"}"/>
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Window x:Class="CheckBoxAll.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CheckBoxAll"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel>
<ListBox x:Name="ListItems" ItemsSource="{Binding ItemCollection}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding isChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" local:CheckBoxExt.IsCheckExt="{Binding ElementName=CheckAll, Path=IsChecked}"/>
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<CheckBox x:Name="CheckAll" Content="Select all"/>
</StackPanel>
</Grid>
</Window>
namespace CheckBoxAll
{
public class CheckBoxExt
{
public static bool GetIsCheckExt(DependencyObject obj)
{
return (bool)obj.GetValue(IsCheckExtProperty);
}
public static void SetIsCheckExt(DependencyObject obj, bool value)
{
obj.SetValue(IsCheckExtProperty, value);
}
// Using a DependencyProperty as the backing store for IsCheckExt. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsCheckExtProperty =
DependencyProperty.RegisterAttached("IsCheckExt", typeof(bool), typeof(CheckBoxExt), new PropertyMetadata((dp,arg) =>
{
if (dp is CheckBox)
{
var checkBox = dp as CheckBox;
checkBox.IsChecked = (bool)arg.NewValue;
}
}));
}
}
I think that in another way, if not by busting, do not do it. If there is any class that performs such an operation, it will most likely have an enumeration at its core.
Just created a trial project in VS2008. So for me, filling the ListView with 1000 items visually took longer than the “Select All” operation.
Here is the code to select all elements:
foreach (ListViewItem listItem in listView_Test.Items)
{
listItem.Checked = true;
}
foreach (ListViewItem listItem in listView_Test.Items)
{
listItem.Checked = false;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question