3

我对 MVVM 还很陌生,最近我开始了一个清理我的代码隐藏的项目,我正在一点一点地将所有内容移至 Model 和 ViewModel。

我的问题是,现在,您如何在没有任何代码的情况下使用 Collection View 进行分组?在阅读了 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;
        }
    }
4

1 回答 1

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然后,假设我没有修改我的代码,您就可以取消该资源。

于 2011-11-16T21:47:59.323 回答