WPF中datagrid控件选中单元格变色或编辑单元格后变色

来源:互联网 发布:小说整站源码带采集 编辑:程序博客网 时间:2024/05/16 09:25
 

不多说,直接上代码~~~

//事件  :编辑单元格后,让单元格变色,以便提醒用户,该单元格数据曾经做过修改

 private void dgSourceData_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
        {
            int colindex = -1;
            int rowindex = -1;

            colindex = this.dgSourceData.CurrentCell.Column.DisplayIndex;//获取选中单元格列号
            rowindex = this.dgSourceData.SelectedIndex;//获取选中单元格行号
            DataGridRow row = (DataGridRow)dgSourceData.ItemContainerGenerator.ContainerFromIndex(rowindex);//获取选中单元格所在行
            DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);//函数调用,获取行中所有单元格的集合
            DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(colindex);//锁定选中单元格(重点)
            if (cell != null)
            {
                dgSourceData.ScrollIntoView(row, dgSourceData.Columns[colindex]);
                cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(colindex);
                cell.Focus();
                cell.Background = new SolidColorBrush(Colors.Red);//OK!问题解决,选中单元格变色


            }
           

        }

 

//获取行中所有单元格集合的函数

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