.NET 5 MVVM模式下DataGrid内ComboBox绑定失效及动态生成列问询
问题1:ComboBox下拉无数据的原因及修复
核心问题:绑定路径错误
你当前的ComboBox绑定规则是查找Window类自身的cboDatas属性,但该属性实际定义在Window的DataContext(即MainWindowViewModel实例)中,需要补充DataContext.前缀修正路径。
额外检查项
确认你在MainWindow的构造函数中已经给DataContext赋值,代码如下:
public MainWindow() { InitializeComponent(); // 必须设置DataContext为ViewModel实例 this.DataContext = new MainWindowViewModel(); }
修正后的ComboBox代码
<ComboBox ItemsSource="{Binding Path=DataContext.cboDatas, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}" DisplayMemberPath="name" SelectedValuePath="id" SelectedValue="{Binding type, Mode=TwoWay}"/>
注:如果你需要把选中值绑定到行数据的对应字段,可以补充上面的
SelectedValuePath和SelectedValue配置,示例中是绑定到feed类的type字段,你可以根据实际需求调整。
问题2:支持动态创建DataGrid列结构
完全支持通过后台代码动态创建列,只需实例化对应类型的列对象,配置属性后添加到DataGrid的Columns集合即可,示例代码如下:
// 动态添加文本列 DataGridTextColumn textCol = new DataGridTextColumn(); textCol.Header = "动态列"; textCol.Binding = new Binding("name"); feeder.Columns.Add(textCol); // 动态添加模板列 DataGridTemplateColumn comboCol = new DataGridTemplateColumn(); comboCol.Header = "动态下拉列"; // 这里可以通过FrameworkElementFactory构建DataTemplate,或者加载XAML资源中的模板 FrameworkElementFactory comboFactory = new FrameworkElementFactory(typeof(ComboBox)); comboFactory.SetBinding(ComboBox.ItemsSourceProperty, new Binding("DataContext.cboDatas") { RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(Window), 1) }); comboFactory.SetValue(ComboBox.DisplayMemberPathProperty, "name"); DataTemplate template = new DataTemplate(); template.VisualTree = comboFactory; comboCol.CellTemplate = template; feeder.Columns.Add(comboCol);
内容的提问来源于stack exchange,提问作者MDP77
相关产品推荐
相关产品推荐

