概述
我正在开发一个WPF应用程序(使用.NET 4.5),其中一部分涉及在DataGrid中显示一些数据。
用户能够在DataGrid中添加新行,并通过其他按钮删除该行。
当用户开始添加无法提交的新行时,我遇到了问题,然后按下删除按钮。
应取消新行,并将DataGrid重置为以前的状态。
但是,DataGrid的NewItemPlaceholder
行将被删除,再也不会显示。
我制作了一个样本工程来演示这个问题。
这里也是一个简短的屏幕。
这是样例应用程序的样子。
复制:
代码
视图模型在ObservableCollection中获取数据,该数据用作集合视图的源。我有一个连接到delete按钮的简单命令。如果用户要添加项(IEditableCollectionView.IsAddingNew
),则尝试使用.CancelNew()
取消collectionView上的操作。但是,当命令完成时,DataGrid将删除其NewItemPlaceholder
。
到目前为止,我已经尝试过:
dataGrid.CanUserAddRows = true
使占位符再次出现,这在一定程度上解决了问题,但这是一个可怕的解决方法,而且很糟糕,而且很糟糕,之后占位符是不可编辑的。this.productsObservable.Remove(this.Products.CurrentAddItem as Product)
。
这不会改变行为,占位符仍然会被移除。this.Products.Remove(this.Products.CurrentAddItem)
。
这会引发异常,这是有意义的:'Remove' is not allowed during an AddNew or EditItem transaction.
还有其他方法可以取消用户的添加并显示NewItemPlaceholder吗?
在示例项目中,为了简单起见,我在VM构造函数中实例化数据。
实际上,我使用了对服务的异步调用,将结果包装在ObservableCollection中,ViewModel实现了INotifyPropertyChanged。业务对象不实现INPC。
示例项目的XAML:
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication3"
Title="MainWindow" Height="250">
<Window.DataContext>
<local:ViewModel />
</Window.DataContext>
<StackPanel Orientation="Vertical">
<Button Command="{Binding DeleteCommand}" Content="Delete row" />
<DataGrid
ItemsSource="{Binding Products}"
CanUserDeleteRows="False"
CanUserAddRows="True"
SelectionMode="Single">
</DataGrid>
</StackPanel>
</Window>
ViewModel,以及一个简单的业务对象:
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows.Data;
using System.Windows.Input;
namespace WpfApplication3
{
public class ViewModel
{
private readonly ObservableCollection<Product> productsObservable;
public ViewModel()
{
this.productsObservable = new ObservableCollection<Product>()
{
new Product() { Name = "White chocolate", Price = 1},
new Product() { Name = "Black chocolate", Price = 2},
new Product() { Name = "Hot chocolate", Price = 3},
};
this.Products = CollectionViewSource.GetDefaultView(this.productsObservable) as IEditableCollectionView;
this.Products.NewItemPlaceholderPosition = NewItemPlaceholderPosition.AtBeginning;
this.DeleteCommand = new DelegateCommand(this.OnDeleteCommandExecuted);
}
public ICommand DeleteCommand { get; private set; }
public IEditableCollectionView Products { get; private set; }
private void OnDeleteCommandExecuted()
{
if (this.Products.IsAddingNew)
{
this.Products.CancelNew();
}
}
}
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
}
}
发布于 2015-04-23 17:20:12
那这个呢?
private void OnDeleteCommandExecuted()
{
if (this.Products.IsAddingNew)
{
this.Products.CancelNew();
this.Products.AddNew();
}
}
您仍然将删除输入错误的行,但是您将添加一个新的(大部分)空行。唯一的问题,尽管我确信它是可修复的,是在数值列中得到默认的0
值,而不是null
。
https://stackoverflow.com/questions/29829818
复制相似问题