WPF DataGrid没有';无法为ICustomTypeDescriptor属性生成列(但Winforms D
本文关键字:属性 Winforms ICustomTypeDescriptor 没有 DataGrid WPF | 更新日期: 2023-09-27 18:26:39
在标题中,我有一个DataGrid和一个ViewModel,它实现了ICustomTypeDescriptor,并在运行时添加了一些属性。
public class PartCloneSettingsController : BaseController, ICustomTypeDescriptor
{
...
private List<StringPropertyDescriptor> generatedProperties;
private void generateProperties()
{
foreach (PartAttributeDefinition item in PartAttributes.DefinedAttributes)
{
var propertyDescriptor = new StringPropertyDescriptor(item.AttributeTitle, typeof(PartCloneSettingsController), item);
// attach value changed handler [ memory leak? TODO: Remove handler at some point...]
propertyDescriptor.AddValueChanged(this, OnGeneratedPropertyChanged);
generatedProperties.Add(propertyDescriptor);
}
}
public PropertyDescriptorCollection GetProperties()
{
// Get All Default (defined) properties
var properties = TypeDescriptor.GetProperties(this, true);
// concat default properties and generated properties into a single collection
var newProperties = new PropertyDescriptorCollection(properties.Cast<PropertyDescriptor>().Concat(generatedProperties).ToArray());
return newProperties;
}
}
XAML中的DataGrid定义:
<DataGrid x:Name="dataGrid" AutoGenerateColumns="True" />
我这样设置ItemsSource:
controller.LoadAssembly(ofd.FileName); // loads the file and creates a ObservableCollection of PartCloneSettingsControllers...
// set data grid source, doesn't create columns for generated properties...
overviewGrid.ItemsSource = controller.PartCloneSettingsControllers
// set data source from a winforms DataGridView which generates columns properly...
((System.Windows.Forms.DataGridView)wfhost.Child).DataSource = controller.PartCloneSettingsControllers;
其中controller.PartCloneSettingsControllers
定义为:
public ObservableCollection<PartCloneSettingsController> PartCloneSettingsControllers { get; private set; }
出于调试目的,我在Winforms控件主机中创建了一个DataGridView,并将相同的ViewModel附加到它上,瞧:Winforms网格创建了所有列,并根据我的需要显示数据,但WPF DataGrid无法为我的自定义属性生成列(它使用普通属性)。
有人有一个使用DataGrid、ICustomTypeDescriptor和AutoGenerateColumn=True的有效解决方案吗(如果我在XAML中手动生成列,它可以正常工作,并且我可以绑定到我的所有属性…)
如果您的PartCloneSettingsControllers
是除object
之外的某个项类型的泛型集合,它将使用泛型参数类型来填充列,而不是使用集合中项的运行时类型。
例如,如果您的集合是IEnumerable<PartCloneSettingsController>
,则网格将仅填充在PartCloneSettingsController
类型(及其基类型)1上声明的属性的列。它不会检查集合中的实际对象,而且由于ICustomTypeDescriptor
在实例级别公开了属性,所以网格不会看到这些属性。
如果您可以选择在类型或集合级别而不是项实例级别公开"动态"属性(例如,使用TypeDescriptionProvider
或ITypedList
),这可能是您的最佳选择。否则,您将不得不使用网格无法推断项类型的集合类型(例如,List<object>
);这将迫使网格检查它遇到的第一个项目,以确定列应该是什么。
1网格最终使用TypeDescriptor.GetProperties(Type componentType)
而不是TypeDescriptor.GetProperties(object component)
来解析属性,因此如果没有实际的项目进行检查,它就无法知道单个项目暴露了哪些"动态"属性