2

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

4

1 回答 1

7

您的选择器会根据它们的DisplayAs值为第二列中的单元格选择一个模板。您必须将模板添加到您的DataGrid.Resources. 然后在第二列中,分配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/>
于 2013-08-09T21:09:53.903 回答