引用WPF数据网格中的单元格

时间:2013-03-28 08:49:30

标签: c# wpf wpfdatagrid

我有一个WPF DataGrid如下:

Items

我的问题是:

  1. 如何根据Price * Quantity?
  2. 执行“总计”列的计算
  3. 有没有办法自动调整表格的列宽以使其看起来更好?
  4. 我的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; }
    }
    

    提前致谢。

1 个答案:

答案 0 :(得分:1)

你需要为你的模型设置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));
    }
}