简体   繁体   English

在WPF DataGrid中引用单元格

[英]Referencing a cell in WPF datagrid

I have a WPF DataGrid as below: 我有一个WPF DataGrid,如下所示:

物品

My questions are: 我的问题是:

  1. How do I perform the calculation of the "total" column based on Price * Quantity? 如何基于价格*数量执行“总计”列的计算?
  2. Is there a way to automatically adjust the column width of the table so that it will look nicer? 有没有一种方法可以自动调整表格的列宽,使其看起来更好?

My cs code is as follows: 我的cs代码如下:

public partial class pgCheckout : Page {

    ObservableCollection<SaleItem> items = new ObservableCollection<SaleItem>();

    public pgCheckout() {
        InitializeComponent();
        dgItems.ItemsSource = items;
    }

    private void btnRemove_Click(object sender, RoutedEventArgs e) {

    }

    private void btnAdd_Click(object sender, RoutedEventArgs e) {
        using (var db = new PoSEntities()) {
            var query = from i in db.Items
                        where i.ItemID.Equals(txtItemID.Text.Trim())
                        select i;
            var itm = query.FirstOrDefault();
            if (itm == null) {
                lblErr.Content = "Invalid Item";
            }
            else {
                lblErr.Content = "";
                items.Add(new SaleItem() {
                    Num = items.Count + 1,
                    ItemID = itm.ItemID,
                    Name = itm.Name,
                    Price = itm.Price,
                    Quantity = 1,
                    Total = 1 //Need to be Price * Quantity
                });
            }
        }
    }
}

class SaleItem {
    public int Num { get; set; }
    public string ItemID { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int Quantity { get; set; }
    public decimal Total { get; set; }
}

Thanks in advance. 提前致谢。

You will need to ipmlement INotifyPropertyChanged interface for your model like this 您将需要像这样为模型ipmlement INotifyPropertyChanged接口

 class SaleItem : INotifyPropertyChanged
{
    public int Num { get; set; }
    public string ItemID { get; set; }
    public string Name { get; set; }

    private decimal price;
    public decimal Price
    {
        get { return price; }
        set
        {
            this.price = value; 
            OnPropertyChanged("Total");
        }
    }

    private decimal quantity;
    public decimal Quantity
    {
        get { return quantity; }
        set
        {
            this.quantity = value; 
            OnPropertyChanged("Total");
        }
    }

    public decimal Total
    {
        get { return Price * Quantity; }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM