开发者

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

I have a WPF 4.0 DataGrid with AutoG开发者_如何学运维enerated 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.


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


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜