Edititem is not allowed for this view list

2019-07-12 09:51发布

问题:

I have tried for hours and hours but I cannot edit the column quantity in datagrid, whenever I do it gives me an error saying that

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

My xaml code is

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

and here is C# code

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

Where am I going wrong? I have tried observable collection also still no solution? Any Help will be appreciated.

回答1:

Assign the List<AddItem> list to the ItemSource instead of Add like so:

Use

DataGrid1.ItemsSource = DATA;

instead of

DataGrid1.Items.Add(DATA);

Other improvements to your code:

  • Use decimal type for all prices (always)
  • Use int type for quantity since quantity represent a number