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?
3 Answers
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 DataGridTemplateColumn
s 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>

- 36,053
- 27
- 163
- 213
-
My DataGrid is bound to a DataTable, I create the DataTable and the columns in the code, since the number of columns is known only in runtime. Is there a way to define new datagridtemplatecolumns this way, but dynamically? – Yoni Apr 30 '11 at 01:04
-
@Yoni: One possibility is to use XamlReader to build your DataGridTemplateColumns on the fly (by string concatenation) and add them then to the columns collection. It looks not very nice but I remember that I have done this also in a similar situation and it worked fine: http://msdn.microsoft.com/en-us/library/cc663033.aspx – HCL Apr 30 '11 at 09:32
If your users usually copy an entire cell at once you can set the DataGrid's SelectionUnit
to Cell
If they copy sections of a cell you're better off overwriting the CellTemplate to display a Label as HCL recommended

- 130,264
- 66
- 304
- 490
I'm fairly sure that if you set the DataGridTextBoxColumn's IsReadOnly property to true, you'll still be able to select and copy the contents.

- 697
- 5
- 5