的方法如下:
<ListView>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="IsSelected" Value="{Binding IsChecked, Mode=TwoWay, RelativeSource={RelativeSource AncestorType={x:Type CheckBox}}}"/>
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
<GridView>
<GridViewColumn>
<GridViewColumn.Header>
<CheckBox x:Name="SelectAllCheckBox" Content="全选" Checked="SelectAllCheckBox_Checked" Unchecked="SelectAllCheckBox_Unchecked"/>
</GridViewColumn.Header>
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListViewItem}}}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<!-- 其他列 -->
</GridView>
</ListView.View>
</ListView>
private void SelectAllCheckBox_Checked(object sender, RoutedEventArgs e)
{
foreach (var item in listView.Items)
{
var listViewItem = listView.ItemContainerGenerator.ContainerFromItem(item) as ListViewItem;
var checkBox = FindVisualChild<CheckBox>(listViewItem);
checkBox.IsChecked = true;
}
}
private void SelectAllCheckBox_Unchecked(object sender, RoutedEventArgs e)
{
foreach (var item in listView.Items)
{
var listViewItem = listView.ItemContainerGenerator.ContainerFromItem(item) as ListViewItem;
var checkBox = FindVisualChild<CheckBox>(listViewItem);
checkBox.IsChecked = false;
}
}
private T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
var child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is T)
return (T)child;
else
{
var childOfChild = FindVisualChild<T>(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
这样,当点击全选CheckBox时,所有的复选框都会被选中;当取消全选CheckBox时,所有的复选框都会取消选中。
领取专属 10元无门槛券
手把手带您无忧上云