c# - 此 View 列表不允许编辑项目

标签 c# wpf xaml datagrid wpfdatagrid

我已经尝试了几个小时,但我无法编辑数据网格中的列数量,每当我这样做时,都会出现错误,指出

An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll Additional information: 'EditItem' is not allowed for this view.

我的xaml代码是

<DataGrid EnableRowVirtualization="True" Grid.Row="3" Grid.ColumnSpan="2" AutoGenerateColumns="False" Name="DataGrid1" IsReadOnly="False" ItemsSource="{Binding Products}" Margin="10,10,10,10" PreviewKeyDown="DataGrid1_PreviewKeyDown" SelectionChanged="DataGrid1_SelectionChanged" CellEditEnding="DataGrid1_CellEditEnding" CanUserAddRows="True" CanUserDeleteRows="True" BeginningEdit="DataGrid1_BeginningEdit" >
    <DataGrid.Columns>
        <DataGridTextColumn Header="Item Name" IsReadOnly="True" Binding="{Binding Path=ItemName}" Width="*"></DataGridTextColumn>
            <DataGridTextColumn Header="Item Price" IsReadOnly="True"  Binding="{Binding Path=ItemPrice}" Width="*"></DataGridTextColumn>
            <DataGridTextColumn x:Name="QuantityColumn" Header="Quantity" IsReadOnly="False"  Binding="{Binding Path=Quantity, Mode=TwoWay}" Width="*"></DataGridTextColumn>
            <DataGridTextColumn Header="Total Price" IsReadOnly="True" Binding="{Binding Path=TotalPrice}" Width="*">
        </DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

这是 C# 代码

List<AddItem> DATA = new List<AddItem>()
{
    new AddItem()
    {
        ItemName = ItemName.Text.ToString(),
        ItemPrice = float.Parse(ItemPrice.Text.ToString()),
        Quantity = quantity.Text,
        TotalPrice = CalculateTotalPrice()
    }
};
DataGrid1.Items.Add(DATA);

public class AddItem
{
    public string ItemName { get; set; }
    public float ItemPrice { get; set; }
    public string Price { get; set; }
    public string Quantity { get; set; }
    public decimal TotalPrice { get; set; }
}

我哪里出错了?我已经尝试了可观察的集合仍然没有解决方案? 任何帮助将不胜感激。

最佳答案

分配 List<AddItem>列表到ItemSource而不是Add像这样:

使用

DataGrid1.ItemsSource = DATA;

而不是

DataGrid1.Items.Add(DATA);

对代码的其他改进:

  • 使用decimal输入所有价格(始终)
  • 使用int输入数量,因为数量代表数字

关于c# - 此 View 列表不允许编辑项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40816294/

相关文章:

c# - 为什么没有设置 ScrollOwner?

c# - AvalonEdit 中的整行高亮显示

wpf - 在WPF中动态添加网格和控件

c# - 如何从数据网格突出显示的行中删除缩进?

c# - 如何循环遍历目录C#中的所有文本文件

c# - 作为代理或重定向器的负载平衡器

wpf - 关于 WPF 的 CystalReports 错误

c# SerialPort WriteTimeout 使用?

c# - 使用 LINQ 的动态表达式。如何找到厨房?

c# - 如何等待或知道 Xamarin Forms 中的多个动画何时完成?