我正在尝试使用SQL db创建一个WPF来跟踪我的订单。
我有5个TextBoxes * 10行(总共50行) 产品项目(名为pur_Items1至10) 价格(以pur_Price1到10命名) 折扣(命名为pur_Discount1到10) ShippingCost(命名为pur_Shipping1到10)和 总项目成本(命名为pur_Total1到10)
不写下60行以下丑陋代码的最佳做法是什么?
double i1 = Convert.ToDouble(pur_Items1.Text);
double p1 = Convert.ToDouble(pur_Price1.Text);
double d1 = Convert.ToDouble(pur_Discount1.Text);
double s1 = Convert.ToDouble(pur_Shipping1.Text);
double t1 = Math.Round(((i1 * p1) - d1) + s1,2);
pur_Total1.Text = Convert.ToString(t1.Text);
我有几个方法,但悲惨地失败
提前谢谢。
答案 0 :(得分:0)
您应该使用DataGrid
来显示动态表格数据。
以下是一个例子:
XAML:
<Window>
<StackPanel>
<Button Content="Submit" HorizontalAlignment="Center" Click="btnSubmit_Click" />
<DataGrid Name="dg"/>
</StackPanel>
</Window>
代码背后:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
dg.ItemsSource = Products;
}
readonly ObservableCollection<Product> Products = new ObservableCollection<Product>();
private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
foreach(var product in Products)
{
//Save product to database
}
Products.Clear();
}
public class Product : INotifyPropertyChanged
{
string _Item;
public string Item
{
get => _Item;
set
{
_Item = value;
RaisePropertyChanged();
}
}
decimal _Price;
public decimal Price
{
get => _Price;
set
{
_Price = value;
RaisePropertyChanged();
RaiseCostChanged();
}
}
decimal _Discount;
public decimal Discount
{
get => _Discount;
set
{
_Discount = value;
RaisePropertyChanged();
RaiseCostChanged();
}
}
decimal _ShippingCost;
public decimal ShippingCost
{
get => _ShippingCost;
set
{
_ShippingCost = value;
RaisePropertyChanged();
RaiseCostChanged();
}
}
public decimal Cost => Price + ShippingCost - Discount;
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged([CallerMemberName]string propertyName = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
protected void RaiseCostChanged() => RaisePropertyChanged(nameof(Cost));
}