WPF 全选,反选,以及获取选中行
Posted cvol
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF 全选,反选,以及获取选中行相关的知识,希望对你有一定的参考价值。
页面代码
<TextBlock> <CheckBox Name="cbAllCreate" Click="CbAllCreate_Click">All</CheckBox> <CheckBox Name="cbInverseCreate" Click="CbInverseCreate_Click">Inverse</CheckBox> </TextBlock> <DataGrid Name="dgCreateTable" AutoGenerateColumns="False" VerticalScrollBarVisibility="Visible" Height="210" EnableRowVirtualization="False"> <DataGrid.Columns> <DataGridCheckBoxColumn Header="Chose" ></DataGridCheckBoxColumn> <DataGridTextColumn Header="Name" Binding="{Binding}" IsReadOnly="True"></DataGridTextColumn> </DataGrid.Columns> </DataGrid>
注:如果不加 EnableRowVirtualization="False" 全选反选会有遗漏的情况,所以一定要加上。
代码
/// <summary> /// 全选 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CbAllCreate_Click(object sender, RoutedEventArgs e) { CbAll(dgCreateTable, cbAllCreate); } /// <summary> /// 反选 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CbInverseCreate_Click(object sender, RoutedEventArgs e) { Inverse(dgCreateTable, cbInverseCreate); } /// <summary> /// 全选 /// </summary> /// <param name="dg"></param> /// <param name="cb"></param> void CbAll(DataGrid dg, CheckBox cb) { dg.IsEnabled = cb.IsChecked != true; for (int i = 0; i < dg.Items.Count; i++) { DataGridRow neddrow = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(i); //获取该行的某列 if (neddrow != null) { FrameworkElement objElement = dg.Columns[0].GetCellContent(neddrow); if (objElement != null) { CheckBox objChk = (CheckBox)objElement; objChk.IsChecked = cb.IsChecked; } } } } /// <summary> /// 反选 /// </summary> /// <param name="dg"></param> /// <param name="cb"></param> void Inverse(DataGrid dg, CheckBox cb) { // cb.IsChecked = false; for (int i = 0; i < dg.Items.Count; i++) { DataGridRow neddrow = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(i); //获取该行的某列 if (neddrow != null) { FrameworkElement objElement = dg.Columns[0].GetCellContent(neddrow); if (objElement != null) { CheckBox objChk = (CheckBox)objElement; objChk.IsChecked = !objChk.IsChecked; } } } }
获取datagrid中选中的行
List<string> GetDataGridList(DataGrid dg) { List<string> list = new List<string>(); for (int i = 0; i < dg.Items.Count; i++) { DataGridRow neddrow = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(i); //获取该行的某列 if (neddrow == null) continue; FrameworkElement objElement = dg.Columns[0].GetCellContent(neddrow); if (objElement == null) continue; CheckBox objChk = (CheckBox)objElement; if (objChk.IsChecked != true) continue; var obj = dg.Columns[1].GetCellContent(neddrow); if (obj == null) continue; var tb = (TextBlock)obj; if (!string.IsNullOrEmpty(tb.Text)) { list.Add(tb.Text); } } return list; }
以上是关于WPF 全选,反选,以及获取选中行的主要内容,如果未能解决你的问题,请参考以下文章