You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 10:54:04