c# - WPF - DataGrid 仅显示基类的属性

标签 c# wpf datagrid

我正在尝试用 List<> 填充 DataGrid的多个对象。这些对象都是基类固有的。我成功地显示了 DataGrid 中的列和行,但是我只看到了基类的属性,而没有看到子类的属性。

不幸的是,我在网上搜索时找不到太多有用的信息。但我仍然是 WPF 和 C# 的新手,所以也许这就是问题所在......

如何让 DataGrid 显示基类和子类的所有属性?

编辑: 我有几个继承自 BaseClass 的类(比如 A、B、C),我有一个类型为 List<BaseClass> 的列表其中包含多种类型的多个对象。我需要在我的 DataGrid 中显示所有不同的子类。

最佳答案

<DataGrid ItemsSource="{Binding}">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Prop1}" />
            <DataGridTextColumn Binding="{Binding Prop2}" />
        </DataGrid.Columns>
</DataGrid>
class Base
{
}

class Derived1: Base
{
    public string Prop1 { get; set; }
}

class Derived2: Base
{
    public string Prop2 { get; set; }
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    this.DataContext = new List<Base>()
    {
        new Derived1(){Prop1 = "Hello"},
        new Derived2() {Prop2 = "World"}
    };
}

这对我有用。我在第一行看到 Hello,在第二行看到 World。

关于c# - WPF - DataGrid 仅显示基类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5605292/

相关文章:

c# - 不能在 'Binding' 类型的 'Source' 属性上设置 'Binding'

wpf - 向 WPF DataGrid 添加不在集合中的额外列

c# - 在适用于 .NET 的 Azure 管理库中创建具有多个声明的 Azure 服务总线策略

c# - smallint转int的datarow字段扩展方法

c# - 查找与工作项关联的变更集或具有特定注释的 TFS Api

c# - 列表框选择事件错误

c# - 在 XAML 中将数据绑定(bind)到 TreeView

c# - 将 DataSet 与 DataGrid 一起使用

apache-flex - 通过 ActionScript 将数据绑定(bind)到 DataGrid

c# - 错误消息 : "Cannot convert type ' string ?' to ' string' "