Can I specify which Columns are editable in a WPF DataGrid?

狂风中的少年 提交于 2019-11-30 14:41:33

The below sample does the trick for one or more columns

  private void Grid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        if (e.Column.Header.ToString() == "COLUMNNAME")
        {
            // e.Cancel = true;   // For not to include 
            // e.Column.IsReadOnly = true; // Makes the column as read only
        }

    } 

Each column has a IsReadOnly Property. Also, the whole DataGrid has the IsReadOnly as well [This does NOT affect the binding, just the ability of the user to edit the field]

EDIT: Rushed an answer, sorry. I can only guess that you should NOT auto-generate columns if possible, so you can control which ones are readonly and which controltemplate goes where... just use the Binding property of the columns so you dont need to autogenerate them.

I got it.... here's what I used:

<DataGrid.Resources>
    <Style TargetType="{x:Type DataGridCell}">
        <Setter Property="IsEnabled" Value="False" />
        <Style.Triggers>
            <DataTrigger Value="PART_IsSelected" Binding="{Binding Path=Column.Header, RelativeSource={RelativeSource Self}}">
                <Setter Property="IsEnabled" Value="True" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</DataGrid.Resources>

If you want, you can use Column.DisplayIndex instead of Column.Header

I'm still not sure why the binding won't work directly and needs to be referenced by a RelativeSource, but at least it works :)

nilam rathod
private void dgTableDetailAdj_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
    foreach (DataGridColumn col in dgTableDetailAdj.Columns)
    {
        if (col.Header.Equals("columnName"))
        {
            col.IsReadOnly = true;
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!