There is a list with Checkboxes, how to click on the button to mark / unmark all Checkboxes?
1 answer
It seems nothing complicated - bindings, commands ...
Suppose I have such a VM, representing one list item:
class ItemVm : Vm { string name; public string Name { get => name; set => Set(ref name, value, nameof(Name)); } bool isChecked; public bool IsChecked { get => isChecked; set => Set(ref isChecked, value, nameof(IsChecked)); } } And the main VM contains a collection of such elements and commands to mark or unmark all the elements:
class MainVM : Vm { public List<ItemVm> Items { get; } public ICommand CheckAllCommand { get; } public ICommand UncheckAllCommand { get; } public MainVM() { Items = new List<ItemVm> { new ItemVm { Name = "Молоко" }, new ItemVm { Name = "Творог" }, new ItemVm { Name = "Сметана" }, new ItemVm { Name = "Кефир" }, new ItemVm { Name = "Сыр" } }; CheckAllCommand = new DelegateCommand( _ => Items.ForEach(item => item.IsChecked = true)); UncheckAllCommand = new DelegateCommand( _ => Items.ForEach(item => item.IsChecked = false)); } } Markup:
<Grid Margin="5"> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <ItemsControl ItemsSource="{Binding Items}"> <ItemsControl.ItemTemplate> <DataTemplate> <CheckBox Content="{Binding Name}" IsChecked="{Binding IsChecked}"/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> <UniformGrid Grid.Row="1" Rows="1" Margin="0,5,0,0"> <Button Content="Check all" Margin="0,0,2.5,0" Command="{Binding CheckAllCommand}"/> <Button Content="Uncheck all" Margin="2.5,0,0,0" Command="{Binding UncheckAllCommand}"/> </UniformGrid> </Grid> If you want to use one CkeckBox instead of two buttons, you can get by with one command that takes a parameter:
CheckAllCommand = new DelegateCommand( o => Items.ForEach(item => item.IsChecked = (bool)o)); then you just need to pass a parameter to the command - the current state of the flag:
<CheckBox Content="Check all" Command="{Binding CheckAllCommand}" CommandParameter="{Binding IsChecked, RelativeSource={RelativeSource Self}}"/> But I did not do this option, because You didn’t describe whether this general checkbox needs to somehow react to setting / clearing checkboxes in the list manually one by one.
|
