2011-11-16 70 views
3

我對MVVM相當陌生,最近我開始了一個清理我的代碼隱藏和點點滴滴的項目,我將所有東西都移動到了Model和ViewModel。如何使用集合視圖MVVM進行分組?

我的問題是,現在,你如何使用集合視圖進行分組而不使用任何代碼?我以爲我已經知道了,在閱讀Stackoverflow上類似問題的答案之後,我仍然無法實現它。可能是一個愚蠢的錯誤,但如果有人可以看看我的代碼並讓我知道他們的想法,我將非常感激。所有的反饋都是很好的反饋,我真的想成爲一個好的程序員:)

這個列表是在Menu類中的ObservableCollection類型的btw。

   <CollectionViewSource x:Key="foods" Source="{Binding Items}"> 
      <CollectionViewSource.GroupDescriptions> 
       <PropertyGroupDescription PropertyName="Category"/> 
      </CollectionViewSource.GroupDescriptions> 
     </CollectionViewSource> 




<ListBox x:Name="selectedMenuItem" Foreground="White" Grid.Column="0" Grid.Row="1" ItemsSource="{Binding Source={StaticResource foods}}" 
        DisplayMemberPath="Name" Background="{x:Null}" BorderThickness="0"> 
           <ListBox.GroupStyle> 
            <x:Static Member="GroupStyle.Default"/> 
           </ListBox.GroupStyle> 
          </ListBox> 




      private CollectionViewSource _items; 
    private Menu _menu = new Menu(); 

    public ICollectionView Items 
    { 
     get 
     { 
      if (_items == null) 
      { 
       _items = new CollectionViewSource {Source = new ObservableCollection<MenuItem>(_menu.MyMenu)}; 
      } 

      return _items.View; 
     } 
    } 

回答

2

我假設你的問題是數據沒有顯示在你的ListBox中?嘗試以編程方式將您的集團以_items,直接綁定您的ListBox.ItemsSource到Items

public ICollectionView Items 
{ 
    get 
    { 
     if (_items == null) 
     { 
      _items = new CollectionViewSource {Source = new ObservableCollection<MenuItem>(_menu.MyMenu)}; 
      _items.GroupDescriptions.Add(new PropertyGroupDescription("Category")); 
     } 

     return _items.View; 
    } 
} 

<ListBox x:Name="selectedMenuItem" Foreground="White" Grid.Column="0" Grid.Row="1" ItemsSource="{Binding Items}"  
        DisplayMemberPath="Name" Background="{x:Null}" BorderThickness="0">  
           <ListBox.GroupStyle>  
            <x:Static Member="GroupStyle.Default"/>  
           </ListBox.GroupStyle>  
          </ListBox> 

然後,您可以廢除的foods資源,假設我沒有boffed我的代碼。

+0

_items.GroupDescriptions.Add(new PropertyGroupDescription(「Category」)); - >訣竅! (加上剛剛使用綁定項目,我早些時候嘗試過,但沒有在ViewModel中添加屬性描述)非常感謝你:) –

+0

有沒有辦法做到這一點,而不需要我的viewmodel中的調度器對象? – Gusdor

相關問題