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

DataGrid内ComboBox的ItemSource失效无法加载Place选项及正常编辑

问题根源

你代码中存在几个核心错误导致功能异常:

  • 给ComboBox的ItemsSource绑定的是Place.Name,这是单个字符串属性,不是可枚举的集合,无法加载下拉选项
  • 没有提前加载所有Place实体的集合到可绑定的上下文属性中
  • 没有设置ComboBox选中值和Device实体PlaceId的关联绑定,编辑后的值无法回写到Device对象
  • 没有设置下拉选项的展示字段,选中后无法正常显示Place的名称

修复步骤

第一步:修改后台C#代码

在UcDevice类中添加公共的Places集合属性,加载Place数据,查询Device时关联加载对应的Place导航属性:

// 新增公共可绑定属性,存储所有Place选项
public ObservableCollection<Place> Places { get; set; }

public UcDevice()
{
    InitializeComponent();
    // 加载所有Place数据到集合
    Places = new ObservableCollection<Place>(_context.Places.ToList());
    DataContext = this; // 绑定当前页面实例,让前端可以访问Places属性
    GetDevices();
}

public void GetDevices()
{
    // 关联加载Place导航属性,确保非编辑状态可以正常显示Place名称
    var devices = _context.Devices.Include(d => d.Place).ToList();
    var uCollection = new ObservableCollection<Device>(devices);
    DgDevice.ItemsSource = uCollection;
}

第二步:修改XAML代码

调整DataGridComboBoxColumn的绑定逻辑,正确关联选项集合、选中值、展示字段:

<DataGridComboBoxColumn 
    Header="نام مجموعه"
    SelectedValuePath="PlaceId"
    DisplayMemberPath="Name"
    SelectedValue="{Binding PlaceId, UpdateSourceTrigger=PropertyChanged}">
    <DataGridComboBoxColumn.ElementStyle>
        <Style TargetType="{x:Type ComboBox}">
            <Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Path=DataContext.Places}" />
        </Style>
    </DataGridComboBoxColumn.ElementStyle>
    <DataGridComboBoxColumn.EditingElementStyle>
        <Style TargetType="{x:Type ComboBox}">
            <Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Path=DataContext.Places}" />
        </Style>
    </DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>

功能说明

  • 下拉选项从全局的Places集合加载,所有行共用同一个选项列表,避免重复加载
  • 选中值通过PlaceId和Device实体绑定,编辑后会自动回写到Device的PlaceId字段
  • 非编辑状态会自动根据PlaceId匹配对应的Place名称展示,不需要额外处理导航属性的绑定

内容的提问来源于stack exchange,提问作者Rasool Aghajani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:57:04