2012-06-01 58 views
0

假設我們有兩個字符串屬性的簡單類,實施INPC:Silverlight的GridView的 - 在屬性更改更新組

public class TestClass : INotifyPropertyChanged 
    { 
     private string _category; 
     public string Category 
     { 
      get { return _category; } 
      set { _category = value; NotifyPropertyChanged("Category"); } 
     } 

     private string _name; 
     public string Name 
     { 
      get { return _name; } 
      set { _name = value; NotifyPropertyChanged("Name"); } 
     } 

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

     public event PropertyChangedEventHandler PropertyChanged; 
    } 

讓我們創建這些一個ObservableCollection並將它們分配到一個PagedCollectionView:

public PagedCollectionView MyItems { get; set; } 

public void Test() 
{ 
    var items = new ObservableCollection<TestClass>(); 
    items.Add(new TestClass { Category = "A", Name = "Item 1" }); 
    items.Add(new TestClass { Category = "A", Name = "Item 2" }); 
    items.Add(new TestClass { Category = "B", Name = "Item 3" }); 
    items.Add(new TestClass { Category = "B", Name = "Item 4" }); 
    items.Add(new TestClass { Category = "C", Name = "Item 5" }); 
    items.Add(new TestClass { Category = "C", Name = "Item 6" }); 
    items.Add(new TestClass { Category = "C", Name = "Item 7" }); 

    MyItems = new PagedCollectionView(items); 
    MyItems.GroupDescriptions.Add(new PropertyGroupDescription("Category")); 
} 
  • 請注意,我們也成立了一個分組的類別

然後,使用MVVM我們在XAML綁定這件事:

<sdk:DataGrid ItemsSource="{Binding Path=MyItems}" /> 

如果我們再進去和編輯一類,說改變「C」的一個s至「A」,例如, gridview處理它精彩。它維護組的崩潰狀態,甚至在需要時添加新的組頭信息!

當我們在視圖模型中(或者例如從另一個gridview綁定到相同的數據中)以編程方式更改類別時,就會出現問題。在這種情況下,類別文本將更新,但該項目不會移動到新的相應組中,不會創建新的組,不會更新行標題等。

如何觸發gridview在GridView編輯功能之外更改屬性時更新其組?

歡迎任何解決方法,但觸發簡單的Refresh()不會消除滾動/摺疊/等。

回答

1

你需要用與EditItem()和commitEdit的()

 // The following will fail to regroup 
     //(MyItems[3] as TestClass).Category = "D"; 

     // The following works 
     MyItems.EditItem(MyItems[3]); 
     (MyItems[3] as TestClass).Category = "D"; 
     MyItems.CommitEdit(); 

     // The following will also fail to regroup    
     //(MyItems[3] as TestClass).Category = "D"; 
     //items[3] = items[3]; 

     // fails as well, surprisingly 
     //(MyItems[3] as TestClass).Category = "D"; 
     //TestClass tmp = items[3]; 
     //items.RemoveAt(3); 
     //items.Insert(3, tmp); 
+0

完美的編輯,謝謝! –

+1

有趣的是,如果過濾了PagedCollectionView,並且編輯將項目的狀態從篩選出來,過濾到篩選中,則只有在定義了分組的情況下,gridview纔會將項目彈出到視圖中。 –

相關問題