【问题标题】:How to set a template for a cell in DataGrid in C#?如何在 C# 中为 DataGrid 中的单元格设置模板?
【发布时间】:2012-11-11 10:38:08
【问题描述】:

我有一个数据网格,其中 ItemsSource 绑定到 LINQ to Entity 查询的结果,其中一列是 EntityCollection 对象。

   private void DataGridRecipientsLoad()
    {
        dataGridRecipients.ItemsSource = from rec in _recipientService.GetAllRecipients()
                                         select rec;
        dataGridRecipients.Columns[7].Visibility = System.Windows.Visibility.Collapsed;
        dataGridRecipients.Columns[8].Visibility = System.Windows.Visibility.Collapsed;            
    }

如何在 C# 中创建一个模板,仅从 Entity Collection 中的项目中取出字符串属性并显示它们?现在单元格是空的。

EntityCollection 由名为 MailingList 的实体组成,我想显示每个实体的 myMailingList.Name

【问题讨论】:

    标签: c# wpf entity-framework datagrid


    【解决方案1】:

    例如,您有客户集合,其中有以下属性:FirstNameLastName

    internal class Customer
    {
        public string FirstName {get; set;}
        public string LastName {get;set;}
    }
    

    然后你可以为它简单的网格视图:

    <DataGrid x:Name="CustomersGridView" AutoGenerateColumns="False" >
            <DataGrid.Columns>
                <DataGridTextColumn Header="First Name" Binding="{Binding Path=FirstName}" />
                <DataGridTextColumn Header="Last Name" Binding="{Binding Path=LastName}" />
            </DataGrid.Columns>
        </DataGrid>
    

    您还需要分配ItemSource(就像您在代码中所做的那样)。 您还可以使用DataGridTemplateColumn 为您的需要编写更灵活的模板。 我建议您阅读有关 xaml 模板的更多信息。 (这个link/another link 有很好的样本)。 p.s.另外,当我看到这样的问题时,我总是建议阅读MVVM

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-23
      • 2016-11-03
      • 1970-01-01
      • 2012-08-04
      • 1970-01-01
      • 2011-04-29
      • 2010-09-18
      • 1970-01-01
      相关资源
      最近更新 更多