CollectionViewSource使用问题

20

我正在尝试基本使用CollectionViewSource,但似乎缺少某些东西,因为它无法正常工作。这是我的XAML代码:

<Window.Resources>
  <CollectionViewSource Source="{Binding loc:MainVM.Instance.MapItems}" x:Key="MapCV">
     <CollectionViewSource.GroupDescriptions>
        <PropertyGroupDescription PropertyName="SourceProject" />
     </CollectionViewSource.GroupDescriptions>
  </CollectionViewSource>
</Window.Resources>

<ListBox ItemsSource="{StaticResource MapCV}" HorizontalContentAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid HorizontalAlignment="Stretch">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="2*"/>
                    <ColumnDefinition Width="2*"/>
                    <ColumnDefinition Width="50"/>
                </Grid.ColumnDefinitions>
                <TextBlock Grid.Column="0" Text="{Binding SourceType, Converter={StaticResource WorkItemTypeToStringConverter}}"/>
                <ComboBox Grid.Column="1" SelectedItem="{Binding DestType}" ItemsSource="{Binding WorkItemTypesForCurrentDestProject, Source={x:Static loc:MainMediator.Instance}, diagnostics:PresentationTraceSources.TraceLevel=High}" DisplayMemberPath="Name" />
                <Button Grid.Column="2" Content="{Binding PercentMapped}"/>
            </Grid>
        </DataTemplate>                                        
    </ListBox.ItemTemplate>
</ListBox>

代码可以编译通过,但是运行应用时出现以下错误:

无法将属性“ItemsSource”中的值转换为类型“System.Collections.IEnumerable”的对象。 
“System.Windows.Data.CollectionViewSource”不是属性“ItemsSource”的有效值。
位于标记文件“WIAssistant;component/main.xaml”的对象“System.Windows.Controls.ListBox”处出错。

这是我正在附加到的集合:

// The mappings used to copy the values of the fields of one WorkItem to another.
public ObservableCollection<WorkItemTypeMapping> WorkItemTypeMappings
{
    get { return (ObservableCollection<WorkItemTypeMapping>)
          GetValue(WorkItemTypeMappingsProperty); }
    set { SetValue(WorkItemTypeMappingsProperty, value); }
}
public static readonly DependencyProperty WorkItemTypeMappingsProperty = 
    DependencyProperty.Register("WorkItemTypeMappings", 
    typeof(ObservableCollection<WorkItemTypeMapping>), typeof(MainMediator), 
    new UIPropertyMetadata(null));

我只想对对象 Project SourceProject 进行简单的分组,不想为此创建树形视图。

1个回答

45
这应该适用于你。
<ListBox ItemsSource="{Binding Source={StaticResource MapCV}}" ...

13
有一天我也会变得聪明,然后就能理解这种东西了!(感谢你的帮助!) - Vaccano
1
这也帮助了我...但是为什么这个有效,而原始变量无效呢? :) - Dmitrii Lobanov
@DmitryLobanov 基本上,CollectionViewSource 本身不是一个集合,但它可以用来访问一个集合。这可能会有所帮助 http://www.zagstudio.com/blog/387#.UyC1nPldV-4 - Bryan Anderson
2
我一直来到这些答案,寻找每种情况的魔法组合。 - Bassem Akl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接