Roberto Salemi

Roberto Salemi

  • NA
  • 146
  • 142k

[WPF] Select all columns

Feb 23 2015 6:06 AM

Hi,

I would insert a column for "Select all" checkbox in each rows.

In my XAML, I inserted:

<DataGridTemplateColumn>
<DataGridTemplateColumn.Header>
<CheckBox Name="chkbxSelectAll" PreviewMouseLeftButtonDown="chkbxSelectAll_PreviewMouseLeftButtonDown"></CheckBox>
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox x:Name="CheckBox"
  PreviewMouseLeftButtonDown="CheckBox_PreviewMouseLeftButtonDown" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

The method CheckBox_PreviewMouseLeftButtonDown:

private void CheckBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var chk = (CheckBox)sender;
var row = VisualTreeHelpers.FindAncestor<DataGridRow>(chk);
var newValue = !chk.IsChecked.GetValueOrDefault();

row.IsSelected = newValue;
chk.IsChecked = newValue;

e.Handled = true;
}

and it works fine.

How can I work "Select all" in the header?

Thanks.


Answers (5)