2010-01-16 523 views
1

我有一個樹視圖可以綁定到很多嵌套的ObservableCollections。樹視圖的每個級別顯示子項目中所有小時的總計總和。例如:樹視圖MVVM ObservableCollection更新

Department 1, 10hrs 
    ├ Team 10, 5hrs 
    │ ├ Mark, 3hrs 
    │ └ Anthony, 2hrs 
    └ Team 11, 5hrs 
    ├ Jason, 2hrs 
    ├ Gary, 2hrs 
    └ Hadley, 1hrs 
Department 2, 4hrs 
    ├ Team 20, 3hrs 
    │ ├ Tabitha, 0.5hrs 
    │ ├ Linsey, 0.5hrs 
    │ └ Guy, 2hrs 
    └ Team 11, 1hr 
    └ "Hadley, 1hr" 

當我修改我Individual.Hours在我的ViewModel類,我想更新我的兩個團隊hours 值和部門太多。

我已經使用NotificationProperties我所有Hours屬性,ObservableCollections在DepartmentsTeamsIndividualsTeams

謝謝,
馬克

回答

4

每個部門的小時數取決於其團隊小時的總和。每個小組的小時數取決於其個人小時的總和。因此,每個團隊都應該傾聽對其任何個人的Hours財產的更改。當檢測到時,它應該爲其自己的Hours財產籌集OnPropertyChanged。同樣,每個Department都應該聽取其團隊的Hours屬性更改。當檢測到時,它應該爲其自己的Hours財產籌集OnPropertyChanged

最終的結果是改變任何個人(或團隊)的小時數都反映在父項中。

Pseduo代碼可以用重構得到很大改善,但給出的答案的精髓:

public class Individual : ViewModel 
{ 
    public int Hours 
    { 
     // standard get/set with property change notification 
    } 

} 

public class Team : ViewModel 
{ 
    public Team() 
    { 
     this.individuals = new IndividualCollection(this); 
    } 

    public ICollection<Individual> Individuals 
    { 
     get { return this.individuals; } 
    } 

    public int Hours 
    { 
     get 
     { 
      // return sum of individual's hours (can cache for perf reasons) 
     } 
    } 

    // custom collection isn't strictly required, but makes the code more readable 
    private sealed class IndividualCollection : ObservableCollection<Individual> 
    { 
     private readonly Team team; 

     public IndividualCollection(Team team) 
     { 
      this.team = team; 
     } 

     public override Add(Individual individual) 
     { 
      individual.PropertyChanged += IndividualPropertyChanged; 
     } 

     public override Remove(...) 
     { 
      individual.PropertyChanged -= IndividualPropertyChanged; 
     } 

     private void IndividualPropertyChanged(object sender, PropertyChangedEventArgs e) 
     { 
      if (e.PropertyName == "Hours") 
      { 
       team.OnPropertyChanged("Hours"); 
      } 
     } 
    } 
} 

public class Department : ViewModel 
{ 
    public Department() 
    { 
     this.teams = new TeamCollection(); 
    } 

    public ICollection<Team> Teams 
    { 
     get { return this.teams; } 
    } 

    public int Hours 
    { 
     get 
     { 
      // return sum of team's hours (can cache for perf reasons) 
     } 
    } 

    // TeamCollection very similar to IndividualCollection (think generics!) 
} 

注意,如果性能成爲一個問題,你可以有集合本身維護小時總。這樣,只要孩子的Hours屬性發生變化,它就可以做一個簡單的添加,因爲它被告知舊值和新值。因此,它知道適用於總量的差異。

1

我affraid你必須明確地呼籲每個人的父(「團隊」)母公司的ObservableCollection容器上的通知。

然後從單個家長處爲宏家長('Department')設置通知事件。

Team.OnPropertyChanged("Individuals") 
+0

謝謝,我以爲是這樣。 – 2010-01-18 13:01:50