WPF DataGrid CheckBox 多选 反选 全选
效果图
实现此效果的必要关键是
Style+DataTemplate
关键代码:
<Window.Resources> <DataTemplate x:Key="CheckBoxDataTemplate"> <Grid> <CheckBox Click="CheckBox_Checked" Uid="{Binding id}" IsChecked="{Binding IsSelect , Mode=TwoWay}"> </CheckBox> </Grid> </DataTemplate> <Style x:Key="CheckBoxStyle" TargetType="{x:Type DataGridCell}"> <Setter Property="ContentTemplate" Value="{StaticResource CheckBoxDataTemplate}"/> </Style> </Window.Resources> <Grid> <DataGrid x:Name="TST" > <DataGrid.Columns> <DataGridCheckBoxColumn CellStyle="{StaticResource CheckBoxStyle}" Header="选择"> <DataGridCheckBoxColumn.HeaderTemplate> <DataTemplate> <CheckBox Content="全选" Uid="-1" Click="CheckBox_Checked"/> </DataTemplate> </DataGridCheckBoxColumn.HeaderTemplate> </DataGridCheckBoxColumn> <DataGridTextColumn Width="15*" Header="顺序" Binding="{Binding id}" /> </DataGrid.Columns > </DataGrid> </Grid>
通过Style中的Setter来引入模板。
模板中则是CheckBox。
这样一来,DataGrid中的数据行的复选框也都可以触发事件了。
那么,在头部中的复选框则是使用修改DataGridCheckBoxColumn.HeaderTemplate来实现头部的复选框。
另外必要说明的是,你可以对绑定类使用INotifyPropertyChanged接口,并 ObservableCollection集合类。
后台的绑定类:
public class TEST : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private bool? isSelect; public int id { get; set; } public bool? IsSelect { get { return isSelect; } set { isSelect = value; OnChanged(new PropertyChangedEventArgs("IsSelect")); } } protected void OnChanged(PropertyChangedEventArgs arg)//具体方法 { PropertyChanged?.Invoke(this, arg); } }
主要实现代码:
ObservableCollection<TEST> ts = new ObservableCollection<TEST>(); public MainWindow() { InitializeComponent(); TST.AutoGenerateColumns = false; TST.CanUserAddRows = false; for (var i = 0; i < 100; i++) { ts.Add(new TEST() { IsSelect = false, id = i }); } TST.ItemsSource = ts; } private void CheckBox_Checked(object sender, RoutedEventArgs e) { var Check = (sender as CheckBox); var CUID = int.Parse(Check.Uid); //全选 if (CUID==-1) { foreach (var item in ts) item.IsSelect = true; Check.Uid = "-2"; return; } //全否选 if (CUID==-2) { foreach (var item in ts) item.IsSelect = false; Check.Uid = "-1"; return; } var IsSelcted = ts[CUID].IsSelect; ts[CUID].IsSelect = (IsSealed ? false : true); var IsSelects = from s in ts where s.IsSelect == true select s; if(IsSelects.Count()==5) { var Text = String.Empty; foreach (var ITEM in IsSelects) Text += ITEM.id + " \n"; MessageBox.Show(Text); } }