我想像这样以编程方式创建一个数据网格
var element = new FrameworkElementFactory(typeof(DataGrid));
if (reflectionInfo.Type.GenericTypeArguments.Count() == 1)
{
var subType = reflectionInfo.Type.GenericTypeArguments[0];
var fields = subType.GetFieldsRecursive("");
foreach (var field in fields)
{
var column = new FrameworkElementFactory(typeof(DataGridTextColumn));
var bindingCol = new Binding(field.Path);
bindingCol.Mode = BindingMode.TwoWay;
bindingCol.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
column.SetBinding(TextBlock.TextProperty, bindingCol);
element.AppendChild(column);
}
}
return element;
但这会引发异常:
System ArgumentException
HResult=0x80070057
Message = The type "DataGridTemplateColumn" must be derived from "FrameworkElement", "FrameworkContentElement" or "Visual3D".
Source = PresentationFramework
Stack monitoring:
for System.Windows.FrameworkElementFactory.set_Type(Type value)
for System.Windows.FrameworkElementFactory..ctor(Type type, String name)
for System.Windows.FrameworkElementFactory..ctor(Type type)
我知道 FrameworkElementFactory 已被弃用,但对我来说是最简单的方法。是否有使用 FrameworkElementFactory 或使用 Xaml 解析转换为 FrameworkElementFactory 的解决方案。