I created the following control:
public ObservableCollection<User> Users { get; set; } = new();
<CollectionViewSource
x:Key="UsersKey"
IsLiveFilteringRequested="True"
Source="{Binding Users}"/>
<ItemsControl x:Name="ItemsControlUsers" ItemsSource="{Binding Source={StaticResource Users}}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding IsSelected}" Checked="CheckBox_OnChecked" Unchecked="CheckBox_OnUnchecked" Content="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
And this is how it looks:
And I want to add a CheckBox of Select all.
I would like it to look like this:
CodePudding user response:
The most obvious solution would be to just use a StackPanel
add a CheckBox
before the ItemsControl
. In this case the item does not belong to the ItemsControl
. Whether this is acceptable or not depends on your requirements.
<StackPanel>
<StackPanel.Resources>
<CollectionViewSource
x:Key="UsersKey"
IsLiveFilteringRequested="True"
Source="{Binding StringItems}"/>
</StackPanel.Resources>
<StackPanel Orientation="Horizontal">
<CheckBox Content="Select all"/>
</StackPanel>
<ItemsControl x:Name="ItemsControlUsers">
<!-- ...other markup. -->
</ItemsControl>
</StackPanel>
Another solution is to use a CompositeCollection
that allows you to bind multiple collections and also add single elements. All of the items are then part of the ItemsControl
.
<Border>
<Border.Resources>
<CollectionViewSource
x:Key="UsersKey"
IsLiveFilteringRequested="True"
Source="{Binding Users}"/>
</Border.Resources>
<ItemsControl x:Name="ItemsControlUsers">
<ItemsControl.ItemsSource>
<CompositeCollection>
<StackPanel Orientation="Horizontal">
<CheckBox Content="Select all"/>
</StackPanel>
<CollectionContainer Collection="{Binding Source={StaticResource UsersKey}}"/>
</CompositeCollection>
</ItemsControl.ItemsSource>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding IsSelected}" Checked="CheckBox_OnChecked" Unchecked="CheckBox_OnUnchecked" Content="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Border>