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

浪尽此生 提交于 2019-11-30 15:26:18

问题


I have a WPF 4.0 DataGrid with AutoGenerated columns. I would like to only allow the user to edit the first column. Is there an easy way of doing this?

I was trying to add a DataGridCell style and set it's editing ability based on either ColumnName (1st column always has the same name) or ColumnIndex, however I cannot figure out the correct XAML for this, or even if it is possible.


回答1:


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
        }

    } 



回答2:


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.




回答3:


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 :)




回答4:


private void dgTableDetailAdj_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
    foreach (DataGridColumn col in dgTableDetailAdj.Columns)
    {
        if (col.Header.Equals("columnName"))
        {
            col.IsReadOnly = true;
        }
    }
}


来源:https://stackoverflow.com/questions/4471934/can-i-specify-which-columns-are-editable-in-a-wpf-datagrid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!