WPF DataGrid在每个单元格中具有不同的UserControl [英] WPF DataGrid with different UserControl in each Cell

查看:208
本文介绍了WPF DataGrid在每个单元格中具有不同的UserControl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想到一个如下所示的数据模型:

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, ...
}

现在我要在Datagrid中显示这些模型,看起来像这样:

Now I want to display these models in a Datagrid which shall look like this:

我该如何实现?请提供一些示例代码。
我用不同类型的DataTemplateSelectors尝试了整整一天,但是我无法使其工作。

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

推荐答案

您的选择器基于他们的 DisplayAs 值,为第二列中的单元格选择一个模板。您必须将模板添加到您的 DataGrid.Resources 中。然后在第二列中,指定 CellTemplateSelector

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

这篇关于WPF DataGrid在每个单元格中具有不同的UserControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆