Search code examples
c#wpfdatagridwpfdatagrid

Disable First Column of First Row in WPF DataGrid


Is there a way (using styles and multi triggers) to always disable the first column of the first row of a DataGrid in a WPF control? This is a templated column which shows combo box in edit mode and text box in normal mode. I'd like this to never go into the edit mode (only this column). The rest of the columns in the row should be able to go into the edit mode.


Solution

  • Yes, it is possible (in other words you want to disable a definite cell), but I would preferable use ValueConverter or CellTemplateSelector to reach the goal.

    In the soution below there is a restriction, that you have to set an AlternationCount property for the DataGrid to the number of the elements in ItemsSource.
    This is a "work around" to get the row index, since DataGridRow has no property to get the index(only a method GetIndex()).

    <DataGrid ItemsSource="{Binding YourItemsCollection}" AutoGenerateColumns="false" AlternationCount="{Binding YourItemsCollection.Count}">
        <DataGrid.CellStyle>
            <Style TargetType="DataGridCell">
                <Style.Triggers>
                    <MultiDataTrigger>
                        <MultiDataTrigger.Conditions>
                            <Condition Binding="{Binding Column.DisplayIndex, RelativeSource={RelativeSource Self}}" Value="0"/>
                            <Condition Binding="{Binding AlternationIndex, RelativeSource={RelativeSource AncestorType=DataGridRow}}" Value="0"/>
                        </MultiDataTrigger.Conditions>
                        <MultiDataTrigger.Setters>
                            <Setter Property="IsEnabled" Value="False" />
                        </MultiDataTrigger.Setters>
                    </MultiDataTrigger>
                </Style.Triggers>
            </Style>
        </DataGrid.CellStyle>
    </DataGrid>