2017-08-25 116 views
0

源代码视图模型是在这里: https://github.com/djangojazz/BubbleUpExample更新时可观察集合中的项目进行更新

的问题是我想要一个视图模型的一个ObservableCollection调用更新,当我更新项目的属性那个集合。我可以更新绑定的数据,但保存集合的ViewModel不会更新,UI也不会更新。

public int Amount 
{ 
    get { return _amount; } 
    set 
    { 
    _amount = value; 
    if (FakeRepo.Instance != null) 
    { 
     //The repo updates just fine, I need to somehow bubble this up to the 
     //collection's source that an item changed on it and do the updates there. 
     FakeRepo.Instance.UpdateTotals(); 
     OnPropertyChanged("Trans"); 
    } 
    OnPropertyChanged(nameof(Amount)); 
    } 
} 

基本上,我需要的成员告诉何地它被称为集合:“嘿,我更新了你,采取通知,告诉你的一部分父我只是无知冒泡例程或调用为了达到这个目的,我发现有限的线程与我所做的略有不同,我知道它可以做很多事情,但我没有运气。下面的图片不需要先点击列。

enter image description here

+0

搜索类似trulyObservableCollection的AddToTrans方法,这里是一个samle:https://stackoverflow.com/questions/1427471/observablecollection-not-noticing-when-item在它改变,甚至与inotifyprop – sTrenat

回答

1

如果您的基础项目遵守INotifyPropertyChanged,则可以使用可观察的集合,这会使属性更改通知冒泡,如下所示。

public class ItemObservableCollection<T> : ObservableCollection<T> where T : INotifyPropertyChanged 
{ 
    public event EventHandler<ItemPropertyChangedEventArgs<T>> ItemPropertyChanged; 


    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs args) 
    { 
     base.OnCollectionChanged(args); 
     if (args.NewItems != null) 
      foreach (INotifyPropertyChanged item in args.NewItems) 
       item.PropertyChanged += item_PropertyChanged; 

     if (args.OldItems != null) 
      foreach (INotifyPropertyChanged item in args.OldItems) 
       item.PropertyChanged -= item_PropertyChanged; 
    } 

    private void OnItemPropertyChanged(T sender, PropertyChangedEventArgs args) 
    { 
     if (ItemPropertyChanged != null) 
      ItemPropertyChanged(this, new ItemPropertyChangedEventArgs<T>(sender, args.PropertyName)); 
    } 

    private void item_PropertyChanged(object sender, PropertyChangedEventArgs e) 
    { 
     OnItemPropertyChanged((T)sender, e); 
    } 
} 
+0

我认为你是从这个答案缺少ItemPropertyChangedEventArgs的一些代码:https://stackoverflow.com/questions/3849361/itempropertychanged-not-working-on-observablecollection-why 。一旦你像你说的那样把它挂上钩子,这个答案就行得通。谢谢。 – djangojazz

+0

这个答案证明是更好的,因为一旦它被连接起来,我需要将它应用到一个更大的解决方案中,这个解决方案有更复杂的部分。这一个将挂钩到OnPropertyChanged的覆盖,因此我可以把任何我想要的父母。 – djangojazz

1

你应该做两件事情来得到它的工作:第一 :你应该重构RunningTotal属性,因此它可以提高属性更改事件。像这样:

private int _runningTotal; 
public int RunningTotal 
{ 
    get => _runningTotal; 
    set 
    { 
     if (value == _runningTotal) 
      return; 
     _runningTotal = value; 
     OnPropertyChanged(nameof(RunningTotal)); 
    } 
} 

你应该做的第二件事情是调用UpdateTotals添加一个DummyTransactionTrans后。一种选择可能是重构的FakeRepo

public void AddToTrans(int id, string desc, int amount) 
{    
    Trans.Add(new DummyTransaction(id, desc, amount)); 
    UpdateTotals(); 
} 
相关问题