即使编辑被取消,WPF DataGrid也在添加新行

时间:2015-09-08 12:05:58

标签: c# wpf xaml datagrid

问题

我使用带有CanUserAddRows="true"的DataGrid,因此用户可以使用底部的占位符行添加条目,但是我得到了不需要的行为:

当用户使用ESC键取消编辑占位符行,然后选择另一行时,DataGrid将刷新并显示另一个空行。

有没有办法阻止添加这个空行?

守则

MainWindow.xaml

<Window x:Class="DataGridTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <DataGrid Name="dgCommands" Margin="5"/>
    </Grid>
</Window>

MainWindows.xaml.cs

using System.Collections.Generic;
using System.Windows;

namespace DataGridTest
{
    public partial class MainWindow : Window
    {
        private List<Command> commands = new List<Command>();

        public MainWindow()
        {
            InitializeComponent();

            commands.Add(new Command
            {
                Request = "Marco",
                Response = "Polo"
            });

            dgCommands.ItemsSource = commands;
        }
    }

    public class Command
    {
        public string Request
        {
            get;
            set;
        }

        public string Response
        {
            get;
            set;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以在EditAction事件中查看CellEditEnding

在yout xaml中向网格添加事件:

<DataGrid Name="dgCommands" Margin="5" CellEditEnding="dataGrid_CellEditEnding" />

并在您的代码中:

private void dataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) {
        //If pressed ESC key
        if (e.EditAction == DataGridEditAction.Cancel) {
            return;
        }
        else {
            //Save new row
        }
    }