WPF DataGrid with different UserControl in each Cell

5.9k views Asked by At

I hava a data model which looks like this:

public class Model
{
    public string DisplayAs {get;set;} // TextBox, CheckBox, ComboBox
    public string Value {get;set;}
    public string DisplayName {get;set;} // Row1, Row2, ...
}

Now I want to display these models in a Datagrid which shall look like this: Datagrid with a other control in each cell

How could I achieve this? Please provide some example code. I tried the whole day with different kind of DataTemplateSelectors but I just can't get it working

1

There are 1 answers

1
Lee Louviere On BEST ANSWER

Your selector selects a template for the cells in the second column based on their DisplayAs value. You have to add the templates to your DataGrid.Resources. Then in the second column, you assign the CellTemplateSelector

public class DynamicDataTemplateSelector: DataTemplateSelector
{
    public override DataTemplate
        SelectTemplate(object item, DependencyObject container)
    {
        FrameworkElement element = container as FrameworkElement;

        if (element != null && item != null && item is Task)
        {
            Model model = item as Model;

            return element.FindResource(model.DisplayAs + "Template");
        }

        return null;
    }
}

<DataGrid>
    <DataGrid.Resources>
        <DataTemplate x:Key="TextBoxTemplate">
            <TextBox Text="{Binding Value}"/>
        </DataTemplate>
        <DataTemplate x:Key="CheckBoxTemplate">
            <CheckBox IsChecked="{Binding Value}"/>
        </DataTemplate>
        <DataTemplate x:Key="ComboBoxTemplate">
            <ComboBox SelectedItem="{Binding Value}"/>
        </DataTemplate>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="RowName">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{DisplayName}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

        <DataGridTemplateColumn Header="Data" 
             CellTemplateSelector="{StaticResource DynamicDataTemplateSelector}"/>
    <DataGrid.Columns>
<DataGrid/>