先看效果图:
.xaml 文件
<Grid Margin="25 0 20 20">
<Grid.RowDefinitions>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<CheckBox Grid.Row="0" Name="Chejy" VerticalContentAlignment="Center" Content="全选/反选" VerticalAlignment="Center" Click="Chejy_Click" />
<Border Grid.Row="1" BorderThickness="1" BorderBrush="DarkGray" >
<ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<ScrollViewer.Content>
<WrapPanel Name="StackPanelContent" Width="410" Orientation="Horizontal"/>
</ScrollViewer.Content>
</ScrollViewer>
</Border>
</Grid>
.cs 文件
Dictionary<string, bool> dicSelPersonnal = new Dictionary<string, bool>();//存储选中集合
#region 全选与反选
public void BindCheckBox()
{
for (int i = 1; i <= 15; i++)
{
CheckBox cb = new CheckBox();
cb.Content = "名称" + i;
cb.Width = 80;
cb.Tag = i;
Thickness thickness = new Thickness(5);
cb.VerticalContentAlignment = VerticalAlignment.Center;
cb.Margin = thickness;
cb.Click += cb_Click;
cb.DataContext = new Test() { ID = i, Name = cb.Content.ToString() };
StackPanelContent.Children.Add(cb);
dicSelPersonnal.Add(cb.Content.ToString(), false);
}
}
void cb_Click(object sender, RoutedEventArgs e)
{
CheckBox cb = sender as CheckBox;
if (cb != null)
{
Test ac = cb.DataContext as Test;
dicSelPersonnal[ac.Name] = (bool)cb.IsChecked;
if (dicSelPersonnal.ContainsKey(ac.Name))
{
dicSelPersonnal[ac.Name] = (bool)cb.IsChecked;
}
SetCheckBoxSelect();
}
}
private void SetCheckBoxSelect()
{
var obj = dicSelPersonnal.Where(a => a.Value == true).ToList();
if (obj.Count == dicSelPersonnal.Count)
{
Chejy.IsChecked = true;
}
else
{
Chejy.IsChecked = false;
}
}
private void Chejy_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < StackPanelContent.Children.Count; i++)
{
CheckBox cb = StackPanelContent.Children[i] as CheckBox;
if (cb != null)
{
cb.IsChecked = (bool)Chejy.IsChecked;
Test ac = cb.DataContext as Test;
dicSelPersonnal[ac.Name] = (bool)cb.IsChecked;
if (dicSelPersonnal.ContainsKey(ac.Name))
{
dicSelPersonnal[ac.Name] = (bool)cb.IsChecked;
}
}
}
}
#endregion
项目下载地址:https://download.csdn.net/download/xianglanyue_net/10359935 点击打开下载链接