【问题标题】:Why are Groups in WPF ListView empty?为什么 WPF ListView 中的组为空?
【发布时间】:2017-06-01 17:27:26
【问题描述】:

我的应用程序中有一个具有三个属性GroupNameItemNameData 的类。我有一个ListView 来按GroupName 对这些类的集合进行分组,并在文本框中显示它们的ItemName 属性。问题是当我运行代码时,组显示正确,但没有一个显示任何成员。

这里是 xaml 代码:

<ListView x:Name="MyList">
    <ListView.GroupStyle>
        <GroupStyle>
            <GroupStyle.ContainerStyle>
                <Style TargetType="{x:Type GroupItem}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate>
                                <Expander IsExpanded="True">
                                    <Expander.Header>
                                        <TextBlock FontWeight="Bold" Text="{Binding Name}"/>
                                    </Expander.Header>
                                </Expander>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </GroupStyle.ContainerStyle>
        </GroupStyle>
    </ListView.GroupStyle>
    <ListView.ItemTemplate>
        <DataTemplate DataType="{x:Type testProgram:MyClass}">
            <TextBlock Text="{Binding ItemName}"/>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

下面是代码:

public partial class MyListView
{
    public MyListView(ObservableCollection<MyClass> items)
    {
        InitializeComponent();
        Items = items;

        var v = CollectionViewSource.GetDefaultView(Items);
        v.GroupDescriptions.Add(new PropertyGroupDescription("GroupName"));
        MyList.ItemsSource = v;
    }

    public ObservableCollection<MyClass> Items { get; set; }
}

当我删除 &lt;ListView.GroupStyle&gt;... 并设置 MyList.ItemsSource = Items; 时,一切都会正确显示。 我怀疑问题出在ItemsSource = vDataType = "{x:Type testProgram:MyClass}"{Binding ItemName} 之间,但我不知道是什么问题或如何解决。

【问题讨论】:

    标签: c# wpf xaml listview data-binding


    【解决方案1】:

    您的ControlTemplate 缺少ItemsPresenter。 WPF 在GroupItem 模板中使用ItemsPresenter 来标记模板展开时实际项目将放置的位置。由于您没有演示者,因此不会显示详细项目。

    尝试将您的模板更改为:

    <Expander IsExpanded="True">
        <Expander.Header>
            <TextBlock FontWeight="Bold" Text="{Binding Name}"/>
        </Expander.Header>
        <Expander.Content>
            <ItemsPresenter />
        </Expander.Content>
    </Expander>
    

    【讨论】:

    • 就是这样。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多