Search code examples
wpfdatagridcheckboxdatagridcolumndatagridcell

WPF - Only specific cells in a DataGridColumn have a CheckBox... Is it ever possible?


My client asks us to have a form with DataGrid, which is pivoted from the standpoint of how the actual data in a database is.

Below is the (simplified) look of my database.

│id|stuff│flag│column│column│column│
------------------------------------
│35| AAA │  0 │ etc. │ blah │ yadda│ 
│58│ BBB │  1 │ etc. │ blah │ yadda│  
│78│ CCC │  0 │ etc. │ blah │ yadda│

Below is what I'm asked to create.

│HEADER│CODE│DATA1│DATA2│DATA3│
-------------------------------
│ID    | #1 │   35│  58│  78│
│STUFF │ #2 │  AAA│  BBB│ CCC│
│FLAG  │ #3 │    0│  1│   0│
│COLUMN│ #4 │ etc.│ etc.│ etc.│
│COLUMN│ #5 │ blah│ blah│ blah│
│COLUMN│ #6 │yadda│yadda│yadda│

The flag column is supposed to be either 0 or 1, so I wanted that column to be a DataGridCheckBoxColumn, but it's pivoted! Of course, I can (with ease) let the cell only accept 1 or 0 in validation process, yet, I'd still want to know if I could ever make a specified cell in a column have a CheckBox.


Solution

  • I would have a look at this WPF horizontal Datagrid answer taking advantage of <RotateTransform Angle="-90"/> to pivot your DataGrid.


    Below is the copied XAML answer @dimaKudr

    <DataGrid.LayoutTransform>
        <TransformGroup>
            <RotateTransform Angle="-90"/>
            <ScaleTransform ScaleX="1" ScaleY="-1" />
        </TransformGroup>
    </DataGrid.LayoutTransform>
    
    <DataGrid.ColumnHeaderStyle>
        <Style TargetType="{x:Type DataGridColumnHeader}"
               BasedOn="{StaticResource {x:Type DataGridColumnHeader}}">
            <Setter Property="LayoutTransform">
                <Setter.Value>
                    <TransformGroup>
                        <RotateTransform Angle="-90"/>
                        <ScaleTransform ScaleX="1" ScaleY="-1" />
                    </TransformGroup>
                </Setter.Value>
            </Setter>
        </Style>
    </DataGrid.ColumnHeaderStyle>
    

    Afterwards, I'd have a look at creating a DataGridTemplateColumn and use a CellTemplate with a CheckBox inside binding to your Flag property, using a Converter to convert the 0 and 1 to true/false

    <DataGrid>
        <DataGrid.Columns>
            <DataGridTemplateColumn x:Name="FlagColumn" Header="Flag" Width="25" IsReadOnly="False">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
                            <CheckBox IsChecked="{Binding Flag, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource FlagConverter}" />
                        </StackPanel>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>