【发布时间】:2015-09-08 12:05:57
【问题描述】:
问题
我使用带有 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;
}
}
}
【问题讨论】:
-
我认为你应该看看 DataGrid 的事件“AddingNewItem”和/或“RowEditEnding”然后你应该能够阻止添加行。
-
@Bertrand 感谢您的提示!尽管
AddingNewItem似乎没有合适的选择,RowEditEnding看起来像是开始的地方。但似乎,取消只会阻止该行显示在 DataGrid 中,它仍会添加到项目列表中,并且 DataGrid 将继续尝试显示它,因此您必须继续取消该事件。