【问题标题】:Combobox not showing groupings组合框不显示分组
【发布时间】:2016-05-11 17:28:23
【问题描述】:

我正在尝试将组合框中的项目组织成组。为此,我创建了一个具有项目和组名称字符串的对象。然后我设置 GroupStyle 和 ItemTemplate 来显示这些值。但是,目前,组合框中只显示项目字符串(并且框有红色边框,表示某种错误)。

这是我的组合框的 xaml:

<ComboBox x:Name="comboBoxProjects" Margin="165,90,28,0" Grid.Column="0" VerticalAlignment="Top" Height="25"
    IsSynchronizedWithCurrentItem="True" SelectedIndex="0" Style="{StaticResource ComboBoxDefault}" 
    ItemsSource="{Binding Path=ProjectClientSelections.ProjectGroupItems,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
    SelectedItem="{Binding Path=ProjectClientSelections.SelectedProject, UpdateSourceTrigger=PropertyChanged}"> 

    <ComboBox.GroupStyle>
        <GroupStyle>
            <GroupStyle.HeaderTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding GroupName}"/>
                </DataTemplate>
            </GroupStyle.HeaderTemplate>
        </GroupStyle>
    </ComboBox.GroupStyle>

    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Project}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>

</ComboBox>

有人知道我哪里出错了吗?

【问题讨论】:

    标签: c# .net wpf xaml combobox


    【解决方案1】:

    在GroupStyle 中,DataContext 不是您的项目(ItemsSource 中包含的类型),而是一个CollectionViewGroup 对象,它是基于您已分组的项目集合形成的。因此,您必须声明到 CollectionViewGroup 中的某个属性的绑定路径,例如,根据您的代码,您可能希望使用Name 属性。见MSDN CollectionViewGroup Class

    将您的 GroupStyle.HeaderTemplate 更改为:

    <DataTemplate>
        <TextBlock Text="{Binding Name}" />
    </DataTemplate>
    

    你没有展示你是如何形成你的 GroupDescriptions 的。如果您还没有对项目进行分组,您可以按照以下方式进行(假设您提供的 XAML 包含在 Window 和 Window 和 GroupBox 的 DataContext 中):

    <Window.Resources>
        <CollectionViewSource
            Source="{Binding ProjectClientSelections.ProjectGroupItems}"
            x:Key="GroupedProjectItems">
            <CollectionViewSource.GroupDescriptions>
                <PropertyGroupDescription
                    PropertyName="GroupName" />
            </CollectionViewSource.GroupDescriptions>
        </CollectionViewSource>
    </Window.Resources>
    

    此更改后GroupBox ItemSource 绑定到以下(直接到CollectionViewSource 资源):

    ItemsSource="{Binding Source={StaticResource GroupedProjectItems}}"
    

    【讨论】:

    • 非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2012-07-14
    • 2013-02-23
    • 2013-12-08
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多