如何在dataGrid1_BeginningEdit事件中获取datagrid单元格的值?

时间:2011-10-13 15:54:03

标签: c# wpf datagrid

当我使用dataGrid1_BeginningEdit事件来停止事件时,我正在尝试检查datagrid单元格的值是否为null。

代码如下,我可以使用'(((TextBox)e.EditingElement).Text'当我做'dataGrid2_CellEditEnding(对象发送者,DataGridCellEditEndingEventArgs e)时'但不能用于下面。

    private void dataGrid2_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
    {
        int column = dataGrid2.CurrentCell.Column.DisplayIndex;
        int row = dataGrid2.SelectedIndex;

        if (((TextBox)e.EditingElement).Text == null)
            return;

非常感谢

7 个答案:

答案 0 :(得分:5)

我认为这会对你有帮助....

    private void DataGrid_BeginningEdit(
        object sender,
        Microsoft.Windows.Controls.DataGridBeginningEditEventArgs e)
    {
        e.Cancel = GetCellValue(((DataGrid) sender).CurrentCell) == null;
    }

    private static object GetCellValue(DataGridCellInfo cell)
    {
        var boundItem = cell.Item;
        var binding = new Binding();
        if (cell.Column is DataGridTextColumn)
        {
            binding
              = ((DataGridTextColumn)cell.Column).Binding
                    as Binding;
        }
        else if (cell.Column is DataGridCheckBoxColumn)
        {
            binding
              = ((DataGridCheckBoxColumn)cell.Column).Binding
                    as Binding;
        }
        else if (cell.Column is DataGridComboBoxColumn)
        {
            binding
                = ((DataGridComboBoxColumn)cell.Column).SelectedValueBinding
                     as Binding;

            if (binding == null)
            {
                binding
                  = ((DataGridComboBoxColumn)cell.Column).SelectedItemBinding
                       as Binding;
            }
        }

        if (binding != null)
        {
            var propertyName = binding.Path.Path;
            var propInfo = boundItem.GetType().GetProperty(propertyName);
            return propInfo.GetValue(boundItem, new object[] {});
        }

        return null;
    }

答案 1 :(得分:4)

我发现了一种不同的方法:

ContentPresenter cp = (ContentPresenter)e.Column.GetCellContent(e.Row);
YourDataType item = (YourDataType)cp.DataContext;

答案 2 :(得分:1)

试试这个 -

(e.EditingEventArgs.Source as TextBlock).Text

答案 3 :(得分:1)

g

答案 4 :(得分:0)

 private void dataGrid2_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (dataGrid2[e.ColumnIndex, e.RowIndex].Value == null)
                {}
        }

答案 5 :(得分:0)

如果您查看DataGridBeginningEditEventArgs,它们会包含一个属性ColumnRow,您可以使用该属性从数据网格中选择单元格。

答案 6 :(得分:0)

这比其他一些可行的答案要简单得多:

    private void DataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
    {
        string content = (e.EditingEventArgs.Source as TextBlock).Text;

        if (String.IsNullOrEmpty(content))
            e.Cancel = true;
    }