是的,这当然是可能的。我不会提供你可以提供的确切代码,因为解决方案取决于你到底需要做什么,但我会尽力而为。
您可以将逻辑放在ViewModel.Load 中,或者创建一个自定义控件,作为 GridView 的包装器。
首先,您需要获取对 GridView 的引用。如果您选择制作控件,只需使用(GridView)this.Children.Single()。要使其在视图模型中工作,请将 ID=Something 添加到您的 GridView,然后调用 (GridView)Context.View.FindControlByClientId("Something")。
GridView(来自 DotVVM.Framework 和来自 BusinessPack 的一个)具有 Columns 属性,您可以将任何您想要的内容附加到它。
grid.Columns.Add(
new GridViewTextColumn() {
HeaderText= "Property 1",
ValueBinding = ...
}
);
您还必须创建值绑定表达式,这有点棘手。问题是 DotVVM 希望在将绑定放入控件之前对其进行编译,但是对于编译,您需要知道控件的确切数据上下文 - 这有点像鸡和蛋的问题。为此,您需要一个 BindingCompilationService,您可以使用构造函数注入并从 DI 容器中获取它,或者只调用 var bindingService = Context.Services.GetRequiredService<BindingCompilationService>()。要获得所需的数据上下文,请使用以下魔法:
var dataContext = grid.GetValueBinding(GridView.DataSourceProperty)
.GetProperty<CollectionElementDataContextBindingProperty>().DataContext;
然后创建绑定和网格列将相当容易:
grid.Columns.Add(
new GridViewTextColumn() {
HeaderText= "Property 1",
ValueBinding = bindingService.Cache.CreateValueBinding("_this.Property1", dataContext)
}
);
您可以为每个属性执行此操作。请注意,CreateValueBinding 辅助方法相对较新,您肯定需要 DotVVM 4.0。