c# - 组合框不显示分组

标签 c# .net wpf xaml combobox

我正在尝试将组合框中的项目组织成组。为此,我创建了一个包含项目和组名称字符串的对象。然后我设置 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>

有人看到我哪里出错了吗?

最佳答案

GroupStyle 中,DataContext 不是您的项目(您的 ItemsSource 中包含的类型),而是一个 CollectionViewGroup 对象,它是基于项目的集合形成的你分组了。因此,您必须声明一个绑定(bind)路径到 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 绑定(bind)到以下(直接到 CollectionViewSource 资源):

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

关于c# - 组合框不显示分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37169512/

相关文章:

c# - 使用反射获取变量名

c# - 将 KeyEventArgs 转换为 KEYDBINPUT 结构

javascript - TimeEntry Js 函数不适用于动态添加的文本框

java - 在 .NET Form/Visual Studio 编辑器中查看 Java GUI?

c# - 在 Datagrid-WPF 中垂直显示水平表格

C# MySql 插入或更新具有 78 个单选按钮的调查表单的命令语法

c# - 当 form[].element 被禁用时,Form.Key 消失

c# - 声音频率 FFT

wpf - UserControl 枚举 DependencyProperty 未绑定(bind)

WPF 扩展器按钮样式,因此它位于扩展器标题内