【问题标题】:ListBox Grouping issue列表框分组问题
【发布时间】:2014-02-17 17:46:55
【问题描述】:

我正在尝试根据我的以下模型对我的收藏进行分组:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Role PersonRole { get; set; }
}

public class Role
{
    public int Id { get; set; }
    public string RoleName { get; set; }
}

我的个人收藏,

public ObservableCollection<Person> PersonList;

集合中填充了三个 Person 对象,其中两个具有相同的角色。

我想根据他们的 RoleName 对我所有的人进行分组。我有以下 XAML:

<Grid.Resources>

        <CollectionViewSource x:Key="cvs" Source="{Binding PersonList}">
            <CollectionViewSource.GroupDescriptions>
                <PropertyGroupDescription PropertyName="PersonRole.RoleName"/>
            </CollectionViewSource.GroupDescriptions>
        </CollectionViewSource>

    </Grid.Resources>

<ListBox ItemsSource="{Binding Source={StaticResource cvs}}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding FirstName}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
        <ListBox.GroupStyle>
            <GroupStyle>
                <GroupStyle.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding PersonRole.RoleName}" FontWeight="Bold" Background="ForestGreen" Margin="0,5,0,0"/>
                    </DataTemplate>
                </GroupStyle.HeaderTemplate>
            </GroupStyle>
        </ListBox.GroupStyle>
    </ListBox>

但是,呈现的 UI 未在列表框中显示分组的 RoleName。此外,我想水平显示分组,其中组水平显示,而分组项目垂直显示。提前感谢任何帮助。

这是我看到的输出:

【问题讨论】:

  • 你想要很多...... ;) 把你的例子发给我们,这样我们就可以工作了。
  • 好吧,实际上我只是想弄清楚为什么没有显示 RoleName。水平分组虽然是次要问题。
  • 只需发布代码。我不想按照所有模板和测试数据的方式工作。你已经有了。

标签: wpf listbox itemscontrol


【解决方案1】:

由于您已经在 CollectionViewSource 中提供了GroupDescriptons,因此 groupStyle 将仅从那里选择属性名称。

您只需CollectionViewGroup 类的Name 属性绑定 以访问应用分组的属性的值。在组样式中,绑定是针对 CollectionViewGroup 类而不是针对您的 Model 类。

所以,这就是你的做法:

<TextBlock Text="{Binding Name}" FontWeight="Bold"
           Background="ForestGreen" Margin="0,5,0,0"/>

关于水平对齐组,您可以将组的ItemsPanelTemplate 设置为VirtualizingStackPanel,将Orientation 设置为Horizontal,这会使您的组水平对齐。

<ListBox.GroupStyle>
   <GroupStyle>
      <GroupStyle.Panel>
         <ItemsPanelTemplate>
           <VirtualizingStackPanel Orientation="Horizontal"/>
         </ItemsPanelTemplate>
      </GroupStyle.Panel>
      <GroupStyle.HeaderTemplate>
        <DataTemplate>
           <TextBlock Text="{Binding Name}" FontWeight="Bold"
                      Background="ForestGreen" Margin="0,5,0,0"/>
         </DataTemplate>
      </GroupStyle.HeaderTemplate>
   </GroupStyle>
</ListBox.GroupStyle>

【讨论】:

  • 谢谢,罗希特。你的解释让我很容易理解。
  • 投了赞成票,因为它解决了一个不相关的问题哈哈。谢谢;)
猜你喜欢
  • 1970-01-01
  • 2015-11-14
  • 1970-01-01
  • 2015-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-14
相关资源
最近更新 更多