WPF DataGrid with different UserControl in each Cell

江枫思渺然 提交于 2019-12-06 14:21:39

问题


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:

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:


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/>


来源:https://stackoverflow.com/questions/18154839/wpf-datagrid-with-different-usercontrol-in-each-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!