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