The Problem
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?
The Code
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;
}
}
}
AddingNewItem
doesn't seem to have a fitting option,RowEditEnding
looks like the place to start. But it seems, cancelling only prevents the row from being shown in the DataGrid, it will still be added to the list of items and the DataGrid will keep trying to show it, so you have to keep cancelling the event.