最简单的选择是ExpandoObject
用于您的视图模型(或DynamicObject
基于类,如果您想添加任何自定义行为):
public class MyEditor
{
public MyEditor()
{
Items = new ObservableCollection<ExpandoObject>
{
CreateItem(1, "John"),
CreateItem(2, "Mary"),
CreateItem(3, "Peter"),
CreateItem(4, "Sarah")
};
}
private ExpandoObject CreateItem(int id, string name)
{
dynamic item = new ExpandoObject();
item.Id = id;
item.Name = name;
return item;
}
public ObservableCollection<ExpandoObject> Items { get; private set; }
}
XAML:
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Items}">
<DataGrid.Columns>
<DataGridTextColumn Header="Id" Binding="{Binding Id}"/>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
</DataGrid.Columns>
</DataGrid>
如果速度对您有意义,那么您的选择是在运行时发出视图模型类型(请参阅参考资料中的类型System.Reflection.Emit
)。