datagridtextcolumn单元格WPF应用程序的设置值

Setting value of datagridtextcolumn cell WPF application

美好的一天

我一定是漏掉了一些非常简单的东西;我有一个带有两个组合框列和一个 datagridtextcolumn 的数据网格。一旦用户为这两个组合框选择了一个值(范围从 1 到 5 的值),将使用这 2 个值进行计算(在组合框选择更改事件中)。我需要将计算结果写入一个单元格(datagridtextcolumn),并根据该值将该单元格的背景更改为特定颜色。我设法找到了组合框中的值和当前行的索引,但是访问相关单元格以写入结果让我变得更好...

到目前为止调用计算的事件处理程序的代码如下:

private void cmbConseq_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var cellInfos = dgDeviation.SelectedCells;
    if (cellInfos == null)
    {
        return;
    }
    var content = cellInfos[0].Column.GetCellContent(cellInfos[0].Item);
    DataRowView row = (DataRowView)content.DataContext;//get the datacontext from FrameworkElement and typecast to DataRowView
    object[] obj = row.Row.ItemArray;//ItemArray returns an object array with single element
    int likely = Convert.ToInt16(obj[0]);
    int cons = Convert.ToInt16(obj[1]);
    int riskValue = new Calculations().riskRankingCalc(likely, cons);

    int rowIndex = dgDeviation.Items.IndexOf(dgDeviation.CurrentItem);

如何将 'riskValue' 变量写入事件处理程序中当前选定行中的相关单元格?

经过一些实验和其他 SO 问题的帮助,对我有用的解决方案是实现以下两个辅助方法:

    public static T GetVisualChild<T>(Visual parent) where T : Visual
    {
        T child = default(T);
        int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < numVisuals; i++)
        {
            Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
            child = v as T;
            if (child == null)
            {
                child = GetVisualChild<T>(v);
            }
            if (child != null)
            {
                break;
            }
        }
        return child;
    }

    public static DataGridCell GetCell(DataGrid grid, int column)
    {
        DataGridRow row = grid.ItemContainerGenerator.ContainerFromIndex(grid.SelectedIndex) as DataGridRow;

        if (row != null)
        {
            DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);

            if (presenter == null)
            {
                grid.ScrollIntoView(row, grid.Columns[column]);
                presenter = GetVisualChild<DataGridCellsPresenter>(row);
            }

            DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            return cell;
        }
        return null;
    }

然后在单元格中进行更改就像调用一样简单:GetCell(myDatagrid, columnIndex).Content = "New Value";