2017-03-02 50 views
0

我有一個數據綁定/查看刷新問題。當我的Worklist類的TotalTask​​Count屬性發生更改時,因爲它未反映在我的視圖中(視圖仍然在列中顯示舊值)。如何將對子對象實例中屬性的更改傳遞給視圖?

我的數據的結構與此類似:

enter image description here

含有數據網格的視圖有其的ItemSource屬性綁定到視圖模型的屬性如下:

<DataContext="{Binding DashBoardVM, Source={StaticResource Locator}}"/> 
    <DataGrid ItemsSource="{Binding SelectedTeamToManage.Worklists}" 
       AutoGenerateColumns = "true"/> 

的View-Model是這樣的:

public class DashBoardViewModel 
    { 
      Observable Collection <Worklist> TeamWorklists = new ObservableCollection <Worklist>(); 

      //Bound to ItemSource of the datagrid 
      public TeamWorkload SelectedTeamToManage 
      { 
       get { return _selectedTeamToManage; } 
       set 
       { 
        _selectedTeamToManage = value; 
        RaisePropertyChanged("SelectedTeamToManage"); 
       } 
      } 
    } 

的TeamWorkload類看起來是這樣的:

public class TeamWorkload 
{ 
    public string TeamName 
    { 
     get { return _teamName; } 
     set { _teamName = value; } 
    } 

    public ObservableCollection<Worklist> WorkLists 
    { 
      get { return _teamWorkLists; } 
      set 
      { 
      _teamWorkLists = value;    
      } 
    } 
} 

和工作列表類實現INotifyPropertyChanged的,看起來像這樣:

public Class Worklist 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    [DisplayName("Total Tasks Count")] 
    public int TotalTasksCount 
    { 
     get { return _totalTasksCount; } 
     set 
     { 
      _totalTasksCount = value; 
      NotifyPropertyChanged("TotalTasksCount"); 
     } 
    } 

    private void NotifyPropertyChanged(string info) 
    { 
     var propChanged = PropertyChanged; 
     if (propChanged != null) 
     { 
      propChanged(this, new PropertyChangedEventArgs(info)); 
     } 
    } 
} 

我只是不知道如何讓視圖模型需要注意的在TeamWorkload可觀察集合中更改並更新數據綁定。我搜索了關於嵌套屬性,collectionchanged事件,冒泡屬性更改事件的所有內容,但我看不到如何實現我在解決方案中找到的任何示例代碼。我甚至不確定這是否是我的問題,但這是我最好的猜測。任何提示都將深表讚賞,因爲我對.NET,MVVM和C#都還是比較新的。

+0

你試過看GlobalPropertyCh嗎事件發生了嗎? –

+0

謝謝拉胡爾 - 我沒有。我會仔細看看的! –

回答

2

聲明PropertyChanged事件與實際實現INotifyPropertyChanged接口不同。

變化

public class Worklist 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 
    ... 
} 

public class Worklist : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 
    ... 
} 

爲了避免這個錯誤,你可能會得到公共基類的所有您的視圖模型類是這樣的:

public class ViewModelBase : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    protected void NotifyPropertyChanged([CallerMemberName] string propertyName = null) 
    { 
     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 
+0

克萊門斯,我不相信我錯過了!那就是訣竅。太感謝了! –

+0

如果您有多個視圖模型類,您可以創建一個實現INotifyPropertyChanged並具有受保護的NotifyPropertyChanged方法的公共基類。 – Clemens

相關問題