Datagrid select rows using a checkbox column

Nov 25, 2008 at 8:45 AM
I have a wpf Datagrid with AutoGenerateColumns=True.
How do I add a checkbox column which can be used to toggle the checked state of the rows?

Nov 25, 2008 at 12:28 PM
Hi,

How about adding the CheckBox to the row header:

<dg:DataGrid Name="dataGrid" ItemsSource="{Binding}" AutoGenerateColumns="True" SelectionMode="Extended">
    <dg:DataGrid.RowHeaderTemplate>
        <DataTemplate>
            <Grid>
                <CheckBox IsChecked="{Binding Path=IsSelected, Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type dg:DataGridRow}}}"/>
            </Grid>
        </DataTemplate>
    </dg:DataGrid.RowHeaderTemplate>
</dg:DataGrid>

The above example uses AutoGeneratedColumns as requested. The RowHeaderTemplate includes a checkbox which has its IsChecked property bound to the IsSelected proeprty of the DataGridRow (we use a relative source binding to navigate up the visual tree).

By teh way, you may find that the invisible grippers whcih are used to change the cell height overlap teh checkbox making it hard to click. If this is a problem for you, you can modify the DataGridRow control template to make the grippers smaller or remove them.

Hope that helps,
Colin E.


Nov 25, 2008 at 12:49 PM
Precise.
It did its job. Regarding the grippers as you mentioned ahead, I have set CanResizeRows to false(This grid won't be needing this), so not an issue at the moment.
I got to know binding can be used to achieve this. Still learning about it.
Thank you.

Note: For others the FindAncestor in Relative Source kept saying some errors in VS.2008 design view, but it compiles and runs fine.
Jun 15, 2009 at 2:45 PM

Hi I need to add header to this row header template... how can I achieve this??? :(

 

Thanks and Regards,

Suba.