gpt4 book ai didi

c# - 无法更新数据网格并将更改保存到数据库

转载 作者:行者123 更新时间:2023-11-30 12:21:27 25 4
gpt4 key购买 nike

我有一个数据网格、一个 ViewModel 中产品类型的 ObservableCollection 和一个 EventToCommand 的实现,如下所示。我想从 Quantity 和 Cost Column 的乘积更新 Total Column 并保存更改,而不使用背后的恶意代码或 Windows Forms DataGridView。我怎样才能做到这一点?数据网格:

<DataGrid x:Name="dataGrid" Margin="5,5,10,5" AutoGenerateColumns="False"  HorizontalAlignment="Stretch" ItemsSource="{Binding ProductList, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Stretch" Height="566"  >
<i:Interaction.Triggers>
<i:EventTrigger EventName="CellEditEnding" SourceObject="{Binding ElementName=Control}">
<cmd:EventToCommand Command="{Binding EndEdit}" PassEventArgsToCommand="True"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<DataGrid.Columns>
<DataGridTextColumn x:Name="Id" Binding="{Binding Path=Id, Mode=TwoWay}" Header="Id"/>
<DataGridTextColumn x:Name="name" Binding="{Binding Path=Name, Mode=TwoWay}" Header="Name"/>
<DataGridTextColumn x:Name="cost" Binding="{Binding Path=Cost, Mode=TwoWay}" Header="Cost"/>
<DataGridTextColumn x:Name="Quantity" Binding="{Binding Path=Quantity, Mode=TwoWay}" Header="Quantity"/>
<DataGridTextColumn x:Name="total" Binding="{Binding Path=Total, Mode=TwoWay}" Header="Total"/>
</DataGrid.Columns>

然后在 ViewModel 中

 private ObservableCollection<Product> _product;
public ObservableCollection<Product> MyProduct
{
get
{
return _product;
}
set
{
Set(ref _product, value);
}
}

public ProductViewModel(IDataService proxy)
{
_proxy = proxy;

LoadCommand = new RelayCommand(DoGetProducts);
EndEdit = new RelayCommand<DataGridCellEditEndingEventArgs>(DoEndEdit);

}

private void DoEndEdit(DataGridCellEditEndingEventArgs obj)
{
DataGridRow row = obj.Row;
Product p = (Product)row.Item;
p.Total = p.Cost*p.Quantity;
_proxy.SaveAll();
}

然后在模型中:

public class DataService : IDataService
{
ProductEntities context;
public DataService()
{
context = new ProductEntities();
}
public ObservableCollection<Product> GetProducts(){
ObservableCollection<Product> products = new ObservableCollection<Product>();
foreach(var p in context.Products.Tolist()){
products.add(p);
}
return products;
}
public void SaveAll()
{
context.SaveChanges();
}
}

当成本和数量发生变化时,数据网格正在加载产品但不会更新总计。此外,不保存数据库中的更改

最佳答案

要更新 DataGrid 中的“总计”列,Product 类应实现 INotifyPropertyChanged接口(interface)并引发 Total 属性的 PropertyChanged 事件:

private double _total;
public double Total
{
get { return _total; }
set { _total = value; OnPropertyChanged("Total"); }
}

为了能够将值保存到数据库中,您需要将 Total 属性映射到数据库表中的列,就像您(希望)对其他列所做的那样.

关于c# - 无法更新数据网格并将更改保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45630030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com