【问题标题】:WPF DataGrid AutoGenerateColumn base class inheritanceWPF DataGrid AutoGenerateColumn 基类继承
【发布时间】:2016-09-13 11:46:36
【问题描述】:

我在 DataGrid 中显示特殊类型的项目时遇到问题。我创建了一个最小的示例。

假设我有一个抽象 BaseClass 和许多继承 ChildClasses

public abstract class BaseClass
{
    public int BaseProperty { get; set; }
}

//Many ChildClasses possible
public class ChildClass : BaseClass
{
    public int ChildProperty { get; set; }
}

我的 DataContext 包含所有项目的集合:

public ObservableCollection<BaseClass> Items { get; set; }

现在我想在 GridView 中显示特殊类型集合的所有项目。为了过滤掉一个类型,我创建了一个CollectionViewSource

<CollectionViewSource Source="{Binding Items}" x:Key="ChildClasses" Filter="ChildClassesFilter"/>

这是使用CollectionViewSource 生成的GridView

<DataGrid ItemsSource="{Binding ChildClasses}"/>

现在我的问题:DataGrid 中,仅自动显示BaseProperty (AutoGenerateColumns)。如何在不描述 XAML 中的属性的情况下强制 WPF 也显示 ChildProperty

或者是否有不同的方法来仅显示我的 GridView 中的特殊类型的项目?

【问题讨论】:

    标签: c# .net wpf xaml gridview


    【解决方案1】:

    您想要执行的操作行不通,因为数据网格列中显示的属性必须存在于Items 集合的每个条目中。只有在 BaseClass 中声明的属性才能保证出现在放入 Items 集合的每个实例中。

    这就是AutoGenerateColumns 不创建子实例列的原因。您有多种解决方法:

    1. 更改您的集合以仅获取您的 ChildClass 的实例
    2. BaseClass 中实现 ChildProperty 并让 ChildClass 重载它
    3. 使用包含您要公开的所有属性的包装器对象,并让它根据包装对象的类型处理获取正确的值和属性。
    4. 您可以使用动态对象和类型描述符来获取每个对象的属性。有一个示例 here 是如何工作的。
    5. 您在 XAML 中声明列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-01
      • 1970-01-01
      • 2020-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多