Search code examples
c#wpfcheckboxdatagridreadonly-attribute

WPF datagrid IsReadOnly exception


I have a datagrid where i have added a Checkbox column. I want the entire datagrid to be IsReadOnly except the Checkbox column. I have tried:

  <DataGrid x:Name="DataGridView_Customer_Information" HorizontalAlignment="Left" Margin="10,200,0,0" VerticalAlignment="Top" Height="410" Width="697" CanUserAddRows="False" IsReadOnly="True" >
        <DataGrid.Columns>
            <DataGridCheckBoxColumn x:Name="CheckBoxSelectRow" IsReadOnly="False"/>
        </DataGrid.Columns>
    </DataGrid>

But i can imagine that <DataGridCheckBoxColumn x:Name="CheckBoxSelectRow" IsReadOnly="False"/> is overruled by the previous statement. Since its only one column that needs to be able to allow edit (allow to checkmark the checkbox) is it possible to make an expection in the IsReadOnly?

Thanks in advanced


Solution

  • You have two options. Both assumes, that DataGrid.AutoGenerateColumns is False.

    1. Remove IsReadOnly="True" from DataGrid element and set IsReadOnly for each column: False for DataGridCheckBoxColumn, True for the rest of columns.

    2. Leave IsReadOnly="True" for DataGrid as is, and instead of DataGridCheckBoxColumn add DataGridTemplateColumn with CheckBox inside template:

      <DataGrid IsReadOnly="True" AutoGenerateColumns="False" ItemsSource="{Binding Guests}">
          <DataGrid.Columns>
              <DataGridTemplateColumn Header="Is invited">
                  <DataGridTemplateColumn.CellTemplate>
                      <DataTemplate>
                          <CheckBox IsChecked="{Binding IsInvited}"/>
                      </DataTemplate>
                  </DataGridTemplateColumn.CellTemplate>
              </DataGridTemplateColumn>
      
              <DataGridTextColumn Header="Name" Binding="{Binding Name}" IsReadOnly="False"/>
          </DataGrid.Columns>
      </DataGrid>
      

    The second approach has another benefit. Default behavior of DataGridCheckBoxColumn is weird - to change check mark you need to select cell first, which is not convenient. CheckBox inside DataGridTemplateColumn accepts user input without selecting cell, and this looks natural.