【问题标题】:WPF Listbox grouping, items with no groupsWPF列表框分组,没有组的项目
【发布时间】:2012-02-24 21:25:22
【问题描述】:

是否可以将列表框(或另一个具有 SelectedItem 的控件)绑定到 ICollectionView,显示如下所示的项目:

  • 项目1名称
  • 项目2名称
  • 父名1
    • Item3Name
    • Item4Name
  • 父名2
    • 项目5名称
    • 项目6名称

用作 CollectionViewSource 视图源的类:

public class Item
{
    public string Name { get; set; }
    public string Parent { get; set; }
}

Item1 和 Item2 的 ParentName 属性设置为 null,Item3 和 Item4 的 ParentName 属性为“ParentName1”,依此类推。

我真的很喜欢列表框的方法,因为只能选择项目,不能选择组。但我可能走错了路。

【问题讨论】:

  • 为什么不使用 WPF TreeView 控件?
  • 因为在树视图中我必须实现逻辑来禁用扩展、设置选定项、禁用组选择等等

标签: wpf


【解决方案1】:

最后我实现了一个样式选择器来设置组样式,如果组为空:

public class NullGroupStyleSelector : StyleSelector
{
    public Style NullGroupStyle { get; set; }
    public Style DefaultStyle { get; set; }

    public override Style SelectStyle(object item, DependencyObject container)
    {
        var element = container as FrameworkElement;
        var group = item as CollectionViewGroup;

        if (element != null && group != null && group.Name == null)
        {
            return this.NullGroupStyle;
        }

        return this.DefaultStyle;
    }
}

并使用模板对样式进行分组:

<Style TargetType="{x:Type GroupItem}" x:Key="NoGroupHeaderStyle">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type GroupItem}">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition />
                        <RowDefinition />
                    </Grid.RowDefinitions>

                    <Border Grid.Row="0">
                        <!-- group name -->
                    </Border>

                    <ItemsPresenter Grid.Row="1" Margin="20,0,0,0" />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

【讨论】:

  • 你有这个解决方案的样本吗?我正在尝试将其应用于列表框中的组,但似乎我无法使用 NullGroupStyleSelector。谢谢。
  • 将其声明为静态资源,并将其绑定到 ListBox 的 GroupStyleSelector 属性。将 ListBox 的 ItemsSource 属性绑定到 CollectionViewSource。
  • 感谢您的评论。您的答案与另一个 stackoverflow.com/a/226117/29544 混合在一起解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-23
  • 1970-01-01
  • 1970-01-01
  • 2011-09-19
  • 2019-06-12
  • 2020-05-19
相关资源
最近更新 更多