日期:2014-05-17  浏览次数:20984 次

WPF,DataGrid编辑单元格数据为什么没有回滚
private void datagrid1_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    string newValue = (e.EditingElement as TextBox).Text;
    int age;
    Int32.TryParse(newValue,out age);
    MessageBox.Show(age.ToString());
    if (age > 100)
        e.Cancel = true;
}

当提交单元格的编辑之后,判断年龄是否大于100,否则回滚。《WPF变成宝典》上说的,把Cancel设为true,就回滚了,但是为什么没有回滚呢?

------解决方案--------------------
private bool cancelling;
private void datagrid1_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    if (cancelling)
    {
        cancelling = false;
        return;
    }
    string newValue = (e.EditingElement as TextBox).Text;
    int age;
    Int32.TryParse(newValue,out age);
    MessageBox.Show(age.ToString());
    if (age > 100)
    {
        cancelling = true;
        DataGrid1.CancelEdit();
    }
}