简体   繁体   English

ObservableCollection.CollectionChanged没有触发

[英]ObservableCollection.CollectionChanged not firing

I have the following interface: 我有以下界面:

数据网格

When an item is added into the DataGrid , the Total column will update according to (price * quantity), and the total TextBox will also have the total of all the rows added. 将项目添加到DataGrid ,“ Total column将根据(价格*数量)进行更新,并且总TextBox也将包含添加的所有行的总计。

However, when I change the quantity of a row, the Total column updates, but the total TextBox does not. 但是,当我更改行的数量时, Total column更新,但TextBox不会更新。

Here is my code, thanks in advance. 这是我的代码,提前谢谢。

 public partial class pgCheckout : Page {

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

    public pgCheckout() {
        InitializeComponent();
        dgItems.ItemsSource = items;
        dgItems.Loaded += SetMinWidths;
        items.CollectionChanged += setTotal;
    }

    public void setTotal(object source, EventArgs e) {
        decimal total = 0;
        foreach(SaleItem i in items) {
            total += i.Total;
        }

        txtTotal.Text = total.ToString();
    }


    public void SetMinWidths(object source, EventArgs e) {
        foreach (var column in dgItems.Columns) {
            if (column.DisplayIndex != 0) {
                column.MinWidth = column.ActualWidth;
                column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
            }
        }
    }

    private void btnRemove_Click(object sender, RoutedEventArgs e) {
        items.RemoveAt(dgItems.SelectedIndex);
    }

    private void btnAdd_Click(object sender, RoutedEventArgs e) {
        bool exist = false;
        foreach (SaleItem i in items) {
            if (i.ItemID.Equals(txtItemID.Text))
                exist = true;
        }

        if (exist) {
            lblErr.Content = "Item already exist";
            txtItemID.Text = "";
        }

        else {

            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";
                    txtItemID.Text = "";
                }
                else {
                    txtItemID.Text = "";
                    lblErr.Content = "";
                    items.Add(new SaleItem() {
                        Num = items.Count + 1,
                        ItemID = itm.ItemID,
                        Name = itm.Name,
                        Price = decimal.Round(itm.Price, 2, MidpointRounding.AwayFromZero),
                        Quantity = 1,
                    });
                }
            }
        }
    }

    private void txtItemID_KeyUp(object sender, KeyEventArgs e) {
        if (e.Key == System.Windows.Input.Key.Enter) {
            btnAdd_Click(txtItemID, e);
        }
    }
}

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");
        }
    }
    public int quantity;
    public int Quantity {
        get { return quantity; }
        set {
            this.quantity = value;
            OnPropertyChanged("Total");
        }
    }

    public decimal Total {
        get { return decimal.Round(Price * Quantity, 2, MidpointRounding.AwayFromZero); }
    }

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

ObservableCollection.CollectionChanged fire when something is added or deleted from the collection not the individual members being update. ObservableCollection.CollectionChanged在集合中添加或删除某些内容时触发,而不是正在更新的个别成员。

...
else 
{
    txtItemID.Text = "";
    lblErr.Content = "";
    SaleItem newItem = new SaleItem() {
                    Num = items.Count + 1,
                    ItemID = itm.ItemID,
                    Name = itm.Name,
                    Price = decimal.Round(itm.Price, 2, MidpointRounding.AwayFromZero),
                    Quantity = 1 };
     newItem.PropertyChanged += 
             new PropertyChangedEventHandler(newSaleItem_PropertyChanged);

    items.Add(newItem);
 }
 ...

And this is the newSaleItem_PropertyChanged : 这是newSaleItem_PropertyChanged

void newSaleItem_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    setTotal(null, null);
}
 ObservableCollection<SaleItem> items = new ObservableCollection<SaleItem>();

must be a propery 必须是一个合理的

change it to 改为

public ObservableCollection<SaleItem> items {get;set;}

and do the new in the constructor 并在构造函数中执行new

or make the get function create new object if one doesn't exist 或者让get函数创建一个新对象(如果不存在)

you must have public getter/setter to use binding 你必须有公共getter / setter才能使用绑定

Your SaleItem must implement INotifyPropertyChanged then you will have PropertyChanged event and you can subscribe to it. 您的SaleItem必须实现INotifyPropertyChanged然后您将拥有PropertyChanged事件并且您可以订阅它。 Using INotifyPropertyChanged will be good for binding. 使用INotifyPropertyChanged将有利于绑定。

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

相关问题 ObservableCollection.CollectionChange在设计时 - ObservableCollection.CollectionChanged at design time ObservableCollection.CollectionChanged 未被调用 - ObservableCollection.CollectionChanged not being called 如何避免在替换所有元素或添加元素集合时多次触发ObservableCollection.CollectionChanged - How to Avoid Firing ObservableCollection.CollectionChanged Multiple Times When Replacing All Elements Or Adding a Collection of Elements WP8 ObservableCollection.CollectionChanged委托崩溃 - WP8 ObservableCollection.CollectionChanged delegate crashing 在ObservableCollection.CollectionChanged上运行昂贵的操作 - Running expensive operations on ObservableCollection.CollectionChanged ObservableCollection的CollectionChanged不触发 - ObservableCollection's CollectionChanged not firing ObservableCollection &lt;&gt; CollectionChanged未触发 - ObservableCollection<> CollectionChanged Not Firing 防止在ObservableCollection.CollectionChanged事件上添加新项目 - Prevent adding the new Item on ObservableCollection.CollectionChanged event ObservableCollection.CollectionChanged在工具栏上未选择正确的DataTemplate - ObservableCollection.CollectionChanged does not select the correct DataTemplate on ToolBar CollectionChanged事件未在静态ObservableCollection上触发 - CollectionChanged Event is not firing on a static ObservableCollection
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM