Tab创建新行并在DataGrid中聚焦新行

时间:2012-11-28 09:00:25

标签: wpf datagrid

我的数据网格存在问题。我的项目正在将Delphi项目转换为.Net。产品所有者希望datagrids具有相同的行为。

当定位在最后一个单元格和制表符上或输入被击中时,应发生以下情况:

  1. 添加了新行
  2. 选择新行中的第一个单元格
  3. 对数据网格的其他要求是:

    • 焦点应该保留在数据网格中,一旦它具有焦点(ALT +组合键是再次离开数据网格的方式)。
    • 数据网格是数据绑定
    • 数据网格用于MVVM
    • 我们使用.net4.0完整个人资料

2 个答案:

答案 0 :(得分:2)

This article有我能找到的最佳解决方案。

我更喜欢使用附加属性而不是行为,因为这使我能够在DataGrid的默认样式中轻松设置它。这是代码:

namespace SampleDataGridApp
{
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Input;

    /// <summary>
    /// An attached behavior that modifies the tab behavior for a <see cref="DataGrid"/>.
    /// </summary>
    public static class DataGridBehavior
    {
        /// <summary>
        /// Identifies the <c>NewLineOnTab</c> attached property.
        /// </summary>
        public static readonly DependencyProperty NewLineOnTabProperty = DependencyProperty.RegisterAttached(
            "NewLineOnTab",
            typeof(bool),
            typeof(DataGridBehavior),
            new PropertyMetadata(default(bool), OnNewLineOnTabChanged));

        /// <summary>
        /// Sets the value of the <c>NewLineOnTab</c> attached property.
        /// </summary>
        /// <param name="element">The <see cref="DataGrid"/>.</param>
        /// <param name="value">A value indicating whether to apply the behavior.</param>
        public static void SetNewLineOnTab(DataGrid element, bool value)
        {
            element.SetValue(NewLineOnTabProperty, value);
        }

        /// <summary>
        /// Gets the value of the <c>NewLineOnTab</c> attached property.
        /// </summary>
        /// <param name="element">The <see cref="DataGrid"/>.</param>
        /// <returns>A value indicating whether to apply the behavior.</returns>
        public static bool GetNewLineOnTab(DataGrid element)
        {
            return (bool)element.GetValue(NewLineOnTabProperty);
        }

        /// <summary>
        /// Called when the value of the <c>NewLineOnTab</c> property changes.
        /// </summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event arguments.</param>
        private static void OnNewLineOnTabChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            DataGrid d = sender as DataGrid;

            if (d == null)
            {
                return;
            }

            bool newValue = (bool)e.NewValue;
            bool oldValue = (bool)e.OldValue;

            if (oldValue == newValue)
            {
                return;
            }

            if (oldValue)
            {
                d.PreviewKeyDown -= AssociatedObjectKeyDown;
            }
            else
            {
                d.PreviewKeyDown += AssociatedObjectKeyDown;
                KeyboardNavigation.SetTabNavigation(d, KeyboardNavigationMode.Contained);
            }
        }

        /// <summary>
        /// Handles the <see cref="UIElement.KeyDown"/> event for a <see cref="DataGridCell"/>.
        /// </summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event arguments.</param>
        private static void AssociatedObjectKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Tab)
            {
                return;
            }

            DataGrid dg = e.Source as DataGrid;

            if (dg == null)
            {
                return;
            }

            if (dg.CurrentColumn.DisplayIndex == dg.Columns.Count - 1)
            {
                var icg = dg.ItemContainerGenerator;

                if (dg.SelectedIndex == icg.Items.Count - 2)
                {
                    dg.CommitEdit(DataGridEditingUnit.Row, false);
                }
            }
        }
    }
}

我的默认样式如下:

<Style TargetType="DataGrid">
    <Setter Property="GridLinesVisibility" Value="None" />
    <Setter Property="KeyboardNavigation.TabNavigation" Value="Contained" />
    <Setter Property="sampleDataGridApp:DataGridBehavior.NewLineOnTab" Value="True" />
    <Setter Property="IsSynchronizedWithCurrentItem" Value="True" />
</Style>

如果最后一列的DataGridCell将IsTabStop设置为false,就像在this example中一样,则上述操作无效。

这是一个错误的解决方法:

private static void AssociatedObjectKeyDown(object sender, KeyEventArgs e)
{               
    if (e.Key != Key.Tab)
    {
        return;
    }

    DataGrid dg = e.Source as DataGrid;

    if (dg == null)
    {
        return;
    }

    int offSet = 1;
    var columnsReversed = dg.Columns.Reverse();
    foreach (var dataGridColumn in columnsReversed)
    {
        // Bug: This makes the grand assumption that a readonly column's "DataGridCell" has IsTabStop == false;
        if (dataGridColumn.IsReadOnly)
        {
            offSet++;
        }
        else
        {
            break;
        }
    }

    if (dg.CurrentColumn.DisplayIndex == (dg.Columns.Count - offSet))
    {
        var icg = dg.ItemContainerGenerator;

        if (dg.SelectedIndex == icg.Items.Count - 2)
        {
            dg.CommitEdit(DataGridEditingUnit.Row, false);
        }
    }
}

答案 1 :(得分:0)

好的,我现在已经和这个问题打了好几个小时了。我已经尝试了几乎所有提出的解决方案,我发现这对我有用......

    private void grid_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Tab)
        {
            if (grid.SelectedIndex == grid.Items.Count - 2 && grid.CurrentColumn.DisplayIndex == grid.Columns.Count - 1)
            {
                grid.CommitEdit(DataGridEditingUnit.Row, false);
                e.Handled = true;
            }
        }
    }

    private void DataGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
    {
        if (grid.SelectedIndex == grid.Items.Count - 2)
        {
            grid.SelectedIndex = grid.Items.Count - 1;
            grid.CurrentCell = new DataGridCellInfo(grid.Items[grid.Items.Count - 1], grid.Columns[0]);
        }
    }

此代码的作用是当您选中最后一行的最后一个单元格并按Tab键时,它会将焦点移动到新行的第一个单元格。这是您所期望的,但这不是默认行为。默认行为是将焦点移动到下一个控件而不提交当前行编辑。这显然是DataGrid中的一个错误,我相信这就是为什么所有提出的解决方案都有一点kluge。我承认,我的解决方案没有那么好,但如果你同意这是错误,我更喜欢这个荒谬的默认行为。

即使网格已排序,此解决方案仍然有效。新输入的行将排序到正确的位置,但焦点将放在新行的第一列。

唯一未解决的问题是,当在新行之前从顶部向下切换到最后一个单元格时,必须先输入两次选项卡,然后才能将焦点移动到新行。我看了一下这个怪癖,最后放弃了。