I use a DataGrid with CanUserAddRows="true"
, so the user can use the placeholder row at the bottom to add entries, but I get unwanted behaviour:
When the user cancels editing of the placeholder row using the ESC
key and then selects another row, the DataGrid will refresh and an additional empty row appears.
Is there a way to prevent this empty row from being added?
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;
}
}
}
You can check EditAction
in CellEditEnding
event:
add event to grid in yout xaml:
<DataGrid Name="dgCommands" Margin="5" CellEditEnding="dataGrid_CellEditEnding" />
and in your code behind:
private void dataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) {
//If pressed ESC key
if (e.EditAction == DataGridEditAction.Cancel) {
return;
}
else {
//Save new row
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.