WPF 列表框分组 Header 未绑定

WPF Listbox Grouping Header Not Binding

我有一个 CollectionViewSource,它按 ObservableCollection 中的 Created 属性分组。分组在列表框中工作,但我无法获取 Header 文本来显示创建日期。

CollectionViewSource 如下:

<Window.Resources>
    <CollectionViewSource x:Key="TaskListColSource" Source="{Binding Path=TaskItems}">
        <CollectionViewSource.SortDescriptions>
            <componentModel:SortDescription PropertyName="Created" />
        </CollectionViewSource.SortDescriptions>

        <CollectionViewSource.GroupDescriptions>
            <PropertyGroupDescription PropertyName="Created" />
        </CollectionViewSource.GroupDescriptions>
    </CollectionViewSource>

</Window.Resources>

我的列表框组样式如下:

        <ListBox.GroupStyle>
            <GroupStyle>
                <GroupStyle.ContainerStyle>
                    <Style TargetType="{x:Type GroupItem}">
                        <Setter Property="Foreground" Value="White" />
                        <Setter Property="Focusable" Value="False"/>
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="{x:Type GroupItem}">
                                    <Expander IsExpanded="True" Foreground="White">
                                        <Expander.HeaderTemplate>
                                            <DataTemplate DataType="{x:Type models:TaskItem}">
                                                <TextBlock  x:Name="asdf" Text="{Binding Created}" Foreground="White"/>
                                            </DataTemplate>
                                        </Expander.HeaderTemplate>
                                        <ItemsPresenter />
                                    </Expander>

                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </GroupStyle.ContainerStyle>
            </GroupStyle>
        </ListBox.GroupStyle>

谁能帮我在相关文本块中显示创建日期?

我按以下方式绑定列表框:

<ListBox x:Name="TaskListBox" ItemsSource="{Binding Source={StaticResource TaskListColSource}}">

您需要像这样为扩展器设置 Header

<Expander IsExpanded="True" Foreground="White" 
          Header="{Binding}">
</Expander>

每个GroupItem中隐含的DataContext就是每个数据项。所以 Header 应该设置到每个数据项(通过 {Binding})。 HeaderTemplate 隐含 DataContext 作为它的 Header 但你没有为它分配任何东西。

编辑:

如果你想要一些 StringFormat,为什么不在 TextBlock 中设置它(让 Header 不变):

 <TextBlock  x:Name="asdf" Text="{Binding Created, StringFormat=dd MMM yy, ConverterCulture=en-GB}" Foreground="White"/>