WPF DataGrid在第一个单元格上按Enter键它正在添加新行我希望它在las单元格上按Enter键添加新行

时间:2018-04-24 10:30:42

标签: wpf datagrid

WPF Datagrid它是在第一个单元格上按Enter时添加新行我希望它按下Datagrid的最后一个单元格后添加新行。

请在此处查看演示应用:

WPFDemo

谢谢你, Jitendra Jadav

1 个答案:

答案 0 :(得分:1)

即使您甚至没有按 ENTER DataGrid也会添加新行。如果您不想要这种行为,那么最好将CanUserAddRows属性设置为false并将项目自己添加到源集合中。像这样:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        dataGrid.CanUserAddRows = false;
        //add blank row
        var itemsSource = dataGrid.ItemsSource as ObservableCollection<ItemModel>;
        if (itemsSource != null)
            itemsSource.Add(new ItemModel());

        Loaded += MainWindow_Loaded;
        dataGrid.PreviewKeyDown += DataGrid_PreviewKeyDown;
    }

    private void DataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if(e.Key == Key.Enter)
        {
            if (Keyboard.FocusedElement is UIElement elementWithFocus)
            {
                if (dataGrid.Columns.Count - 1 == dataGrid.CurrentCell.Column.DisplayIndex)
                {
                    var itemsSource = dataGrid.ItemsSource as ObservableCollection<ItemModel>;
                    if (itemsSource != null)
                    {
                        var newItem = new ItemModel();
                        itemsSource.Add(newItem);

                        dataGrid.SelectedItem = newItem;
                        Dispatcher.BeginInvoke(new Action(()=> 
                        {
                            DataGridRow row = dataGrid.ItemContainerGenerator.ContainerFromItem(newItem) as DataGridRow;
                            DataGridCell cell = Helper.GetCell(dataGrid, row, 0);
                            if (cell != null)
                                dataGrid.CurrentCell = new DataGridCellInfo(cell);
                        }), DispatcherPriority.Background);
                    }

                }
                else
                {
                    elementWithFocus.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                    e.Handled = true;
                }
            }
        }
    }

    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        Helper.SelectRowByIndex(dataGrid, 0);
    }
}
相关问题