Monday 22 October 2012

WPF DataGrid CheckBox Column requires two clicks to change state

While using a WPF DataGrid and a CheckBox column I realised that it was taking two Mouse clicks to change the state of the CheckBox.

I found a good post by Mike Borozdin which explains how to work around this ‘issue’;

http://www.mikeborozdin.com/post/WPF-DataGrid-CheckBox-Single-Click-CheckingUnchecking.aspx

Basically, if instead of adding a CheckBox column, you add a TemplateColumn, and enclose a CheckBox within the DataTemplate, this works around the ‘issue’;

<DataGrid Name="dgProducts" AutoGenerateColumns="False" CurrentCellChanged="dgProducts_CurrentCellChanged">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}"/>
        <DataGridTextColumn Header="Price" Binding="{Binding Path=Price}"/>
        <DataGridTemplateColumn Header="In Stock">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <CheckBox IsChecked="{Binding Path=IsInStock, UpdateSourceTrigger=PropertyChanged}">
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

No comments:

Post a Comment