Silverlight DataGrid BeginEdit方法导致CellEditEnded事件

时间:2012-04-05 16:56:29

标签: c# silverlight datagrid

我要求用户应该能够点击网格中的(可编辑的)单元格,并且它立即进入编辑模式,而不必双击F2。为此,我添加了一个行为:

public class AutomaticallyEditGridBehavior : Behavior<DataGrid>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        if (AssociatedObject.IsReadOnly)
        {
            return;
        }

        AssociatedObject.CurrentCellChanged += OnCurrentCellChanged;
    }

    private void OnCurrentCellChanged(object sender, EventArgs e)
    {
        // Check our column is not readonly first
        if (AssociatedObject.CurrentColumn.IsReadOnly)
        {
            return;
        }

        AssociatedObject.BeginEdit();
    }
}

我在编辑单元格时也有一些逻辑,所以我添加了另一种行为:

public class CellEditEndedBehavior : Behavior<DataGrid>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.CellEditEnded += CellEditEnded;
    }

    private void CellEditEnded(object sender, DataGridCellEditEndedEventArgs e)
    {
        if (e.EditAction != DataGridEditAction.Commit)
        {
            return;
        }

        if (AssociatedObject.SelectedItem == null)
        {
            return;
        }

        // Some processing and logic to get next editable item

        // Set the focus to the next item and begin editing
        AssociatedObject.SelectedItem = nextEditableItem;
        AssociatedObject.CurrentColumn = e.Column;
        AssociatedObject.Focus();
        AssociatedObject.BeginEdit();
    }
}

我发现当我单击一个单元格时,第一个行为会运行,但在有机会编辑该单元格之前,CellEditEnded事件已经触发。因此,焦点移动到下一个对象而不是刚刚单击的单元格。

为什么在单元格实际编辑之前触发此事件?有更好的方法吗?

0 个答案:

没有答案