【问题标题】:WPF DataGrid is adding a new row even though edit was cancelled即使取消编辑,WPF DataGrid 仍在添加新行
【发布时间】: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 将继续尝试显示它,因此您必须继续取消该事件。

标签: c# wpf xaml datagrid


【解决方案1】:

您可以在CellEditEnding事件中查看EditAction:

在 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
        }
    }

【讨论】:

  • 正如我所说,即使DataGridEditAction 设置为Cancel,也会添加空行。而且您不必自己保存该行,它由DataGrid 处理。这就是问题所在 - 我无法控制行的添加。
猜你喜欢
  • 2013-07-30
  • 1970-01-01
  • 2013-12-25
  • 2015-04-06
  • 1970-01-01
  • 1970-01-01
  • 2018-12-14
  • 1970-01-01
  • 2011-08-23
相关资源
最近更新 更多