WPF datagrid - enable selecting, disabling text input

Yoni picture Yoni · Apr 29, 2011 · Viewed 9.9k times · Source

I have a C# WPF Datagrid, with a checkbox column, hyperlink columns and text columns. My DataGrid is bound to a DataTable. The columns are not auto generated, but I do create them in code dynamically, since the number of columns is not known in advance. I would like to enable the text in the cells to be selected (for ctrl+c purpose) but yet disable editing. I don't want the text to be changed. Anyone can help?

Answer

HCL picture HCL · Apr 29, 2011

One possibility is probably be to use a DataGridTemplateColumn:

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBox IsReadOnly="True" Text="{Binding YourProperty,Mode=OneWay}"/>                            
        </DataTemplate>                        
    </DataGridTemplateColumn.CellTemplate>                    
</DataGridTemplateColumn>

This works also with Checkboxes, add a CheckBox, Bind its IsChecked and use as the content a TextBox that is set to IsReadOnly.

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <CheckBox IsChecked="{Binding YourBooleanValue}">
                <TextBox IsReadOnly="True" Text="YourCopyableTextOrABindingToText"/>
            </CheckBox>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

If you want to have the checkbox readonly, set its Enabled-property to false. However in this case, you have to declare the TextBox not as a child but as a sibling of the CheckBox (use a grid or a StackPanel) for this.

If you want to make data readonly for the whole DataGrid, use:

<DataGrid IsReadOnly="True">

THis is also possible for columns:

<DataGridTextColumn IsReadOnly="True">

If you want to define it per row, you have to use DataGridTemplateColumns and bind the IsReadOnly-proeprty of the edit-control.

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBox IsReadOnly="{Binind YourReadOnlyProperty}" Text="{Binding YourProperty,Mode=OneWay}"/>
        </DataTemplate>                        
    </DataGridTemplateColumn.CellTemplate>                    
</DataGridTemplateColumn>