DataGrid sample with SelectAll Checkbox
Here is a one way of getting the SelectAll functionality in DataGrid
the DataGrid is defined like this
<my:DataGrid x:Name=”myDataGrid”
VerticalAlignment=”Top”
Width=”350″
Height=”300″
Grid.Column=”0″
AutoGenerateColumns=”False”>
<my:DataGrid.Columns>
<my:DataGridTemplateColumn Width=”80″>
<my:DataGridTemplateColumn.Header>
<CheckBox HorizontalAlignment=”Center”
Click=”chk_Click”
VerticalAlignment=”Center”
x:Name=”chkAll”></CheckBox>
</my:DataGridTemplateColumn.Header>
<my:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox x:Name=”chk”
HorizontalAlignment=”Center”
HorizontalContentAlignment=”Center”></CheckBox>
</DataTemplate>
</my:DataGridTemplateColumn.CellTemplate>
</my:DataGridTemplateColumn>
<my:DataGridTextColumn Header=”First Name”
Width=”100″
DisplayMemberBinding=”{Binding FirstName}”
FontSize=”20″ />
<my:DataGridTextColumn Header=”Last Name”
Width=”100″
DisplayMemberBinding=”{Binding LastName}”
FontSize=”20″ />
</my:DataGrid.Columns>
</my:DataGrid>
when the rows are being loaded we keep a track of all the checkboxes in the LoadingRow eventhandler
void myDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
CheckBox chk = myDataGrid.Columns[0].GetCellContent(e.Row) as CheckBox;
chk.IsChecked = false;
checkboxes.Add(chk);
}
and when the checkbox in the header is clicked we check/uncheck each of the items in the list of checkboxes.
void chk_Click(object sender, RoutedEventArgs e)
{
CheckBox chk = sender as CheckBox;
bool check = chk.IsChecked.Value;
foreach (CheckBox chkbox in checkboxes)
chkbox.IsChecked = check;
}
you can download the code here
Note:
This will work only if datagrid has no scrolling.
I will post couple more, one that will work with scrolling and other changing the class to add a property so we can use databinding.
[...] gives us A select all checkbox in the datagrid and with [...]
2008 September 23 - Links for today « My (almost) Daily Links
September 23, 2008
[...] to me… something we’ll get used to seeing and being familiar with as the blog articles roll past. DataGrid sample with SelectAll Checkbox Lee reappeared with this post of xaml code for a datagrid with a select All checkbox, then [...]
Silverlight Cream for September 22, 2008 -- #374
September 25, 2008