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

如何在编辑后将含自定义用户控件的WPF DataGrid列标记为脏状态

解决WPF DataGrid自定义多选控件编辑后行无变更通知的问题

核心问题分析

点击多选控件的+按钮时,DataGrid未进入单元格编辑状态,导致后续变更无法触发RowEditEnding事件,行也不会被标记为“脏”状态。下面是具体解决方案:


1. 点击按钮时手动触发DataGrid单元格编辑

在你的MultiSelectCell控件的+按钮点击事件中,添加代码找到父级DataGridCell并触发编辑状态,让DataGrid感知到编辑操作开始:

private void PlusButton_Click(object sender, RoutedEventArgs e)
{
    // 查找父级DataGridCell
    var cell = FindVisualParent<DataGridCell>(sender as FrameworkElement);
    if (cell != null && !cell.IsEditing)
    {
        cell.BeginEdit();
    }

    // 原有打开选择对话框的逻辑
    var dialog = new ActiveIngredientSelectionDialog();
    if (dialog.ShowDialog() == true)
    {
        // 更新选中项集合
        ChosenItems = dialog.SelectedItems;
    }
}

// 通用视觉父级查找方法
private T FindVisualParent<T>(DependencyObject child) where T : DependencyObject
{
    var parent = VisualTreeHelper.GetParent(child);
    if (parent == null) return null;
    
    return parent is T typedParent ? typedParent : FindVisualParent<T>(parent);
}

2. 确保绑定集合为ObservableCollection

你的ActiveIngredients属性必须使用ObservableCollection<T>而非普通List<T>,这样集合元素变更时才能自动触发PropertyChanged通知:

private ObservableCollection<ActiveIngredient> _activeIngredients;
public ObservableCollection<ActiveIngredient> ActiveIngredients
{
    get => _activeIngredients;
    set
    {
        _activeIngredients = value;
        OnPropertyChanged(nameof(ActiveIngredients));
    }
}

3. 选择完成后手动提交编辑标记行脏

在对话框确认选择、更新ChosenItems后,手动触发DataGrid提交编辑,确保行状态被标记为已变更:

// 在MultiSelectCell的ChosenItems属性变更回调中添加
private void OnChosenItemsChanged()
{
    var cell = FindVisualParent<DataGridCell>(this);
    if (cell == null) return;

    var row = FindVisualParent<DataGridRow>(cell);
    var dataGrid = FindVisualParent<DataGrid>(row);
    
    if (dataGrid != null)
    {
        // 提交单元格编辑,标记行脏
        dataGrid.CommitEdit(DataGridEditingUnit.Cell, true);
        // 如果需要触发行级编辑结束事件,可调用:
        // dataGrid.CommitEdit(DataGridEditingUnit.Row, true);
    }
}

额外检查项

  • 确认DataGrid的CanUserEditRows属性设为True(默认是True,但最好显式确认)
  • 确保ChosenItems的绑定UpdateSourceTrigger=PropertyChanged已正确设置(你代码中已经配置,无需修改)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 19:40:20