开发者

WPF datagrid - enable selecting, disabling text input

开发者 https://www.devze.com 2023-03-01 07:13 出处:网络
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,

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 n开发者_开发问答umber 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?


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>


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消