Search code examples
c#wpfwpfdatagrid

Edit Datagrid combobox or textbox


I have a datagrid and I want the users to be able to edit the values in one of the columns. However depending on the value in another column I either need to have them enter the values in a textbox (other column value = 0) or pick a value from a combobox (other column value > 00) that I will populate from a Dictionary.

How would I do something like this?


Solution

  • You can define the TemplateColumn for your DataGrid and define its CellTemplate as below:

     <DataGrid>
            <DataGrid.Columns>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <ContentControl x:Name="ContentPlaceholder">
                                <ContentControl.Style>
                                    <Style TargetType="{x:Type ContentControl}">
                                        <Setter Property="ContentTemplate">
                                            <Setter.Value>
                                                <DataTemplate>
                                                    <ComboBox />
                                                </DataTemplate>
                                            </Setter.Value>
                                        </Setter>
                                        <Style.Triggers>
                                            <DataTrigger Binding="{Binding COLUMNTWOPROPERTY}" Value="0">
                                                <Setter Property="ContentTemplate">
                                                    <Setter.Value>
                                                        <DataTemplate>
                                                            <TextBox Text="{Binding PROPERTYFORTEXTBOX}"/>
                                                        </DataTemplate>
                                                    </Setter.Value>
                                                </Setter>
                                            </DataTrigger>
                                        </Style.Triggers>
                                    </Style>
                                </ContentControl.Style>
                            </ContentControl>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    

    Here COLUMNTWOPROPERTY is the value which decides whether cell should show textbox or combobox.

    Thanks