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

时间:2016-03-29 09:24:06

标签: c# wpf datagrid datagridcomboboxcolumn datagridtextcolumn

美好的一天

我必须在这里找到一些非常简单的东西;我有一个带有两个组合框列和一个datagridtextcolumn的数据网格。一旦用户选择了这两个组合框的值(范围从1到5),就用这两个值(在组合框选择改变事件上)进行计算。我需要将计算结果写入单元格(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'变量写入eventhandler中当前所选行的相关单元格?

1 个答案:

答案 0 :(得分:1)

经过一些实验和其他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 =&#34; New Value&#34 ;;