开发者

How can I disable editing cells in a WPF Datagrid?

开发者 https://www.devze.com 2023-03-21 14:48 出处:网络
I\'m constructing a datagrid in Windows Presentation Foundation, and I have a problem. When a user double-clicks on a cell in my datagrid, the cell goes into edit mode. I want to prevent that. Instead

I'm constructing a datagrid in Windows Presentation Foundation, and I have a problem. When a user double-clicks on a cell in my datagrid, the cell goes into edit mode. I want to prevent that. Instead I want users to be able to se开发者_如何学Clect the full row - not edit values in it.

How can I make it so that double-clicks select the full row instead of putting the clicked-on cell in edit mode?


The WPF DataGrid has an IsReadOnly property that you can set to True to ensure that users cannot edit your DataGrid's cells.

You can also set this value for individual columns in your DataGrid as needed.


The DataGrid has an XAML property IsReadOnly that you can set to true:

<my:DataGrid
    IsReadOnly="True"
/>


I see users in comments wondering how to disable cell editing while allowing row deletion : I managed to do this by setting all columns individually to read only, instead of the DataGrid itself.

<DataGrid IsReadOnly="False">
    <DataGrid.Columns>
        <DataGridTextColumn IsReadOnly="True"/>
        <DataGridTextColumn IsReadOnly="True"/>
    </DataGrid.Columns>
</DataGrid>


If you want to disable editing the entire grid, you can set IsReadOnly to true on the grid. If you want to disable user to add new rows, you set the property CanUserAddRows="False"

<DataGrid IsReadOnly="True" CanUserAddRows="False" />

Further more you can set IsReadOnly on individual columns to disable editing.


If you're binding to an ObservableCollection<T> and your DataGrid has AutoGenerateColumns="True" because you don't want to mess with individual column definitions in your XAML, it seems that you can use the ReadOnlyAttribute from System.ComponentModel:

using System.ComponentModel;

public class SomeObject
{
    public bool ClickableCheckboxColumn { get; set; } = true;
    [ReadOnly(true)]
    public string UneditableTextColumn { get; set; } = string.Empty;
}
0

精彩评论

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

关注公众号