WPF列表框分组,没有分组的项

6

是否可以将列表框(或其他具有SelectedItem的控件)绑定到ICollectionView,并以如下方式显示项目:

  • Item1Name
  • Item2Name
  • ParentName1
    • Item3Name
    • Item4Name
  • ParentName2
    • Item5Name
    • Item6Name

用作CollectionViewSource视图源的类:

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

Item1和Item2的ParentName属性被设置为null,Item3和Item4的ParentName属性为"ParentName1",以此类推。

我非常喜欢listbox的方法,因为只有项目可以被选择,组是不可选的。但我可能走了错误的路线。


为什么不使用WPF TreeView控件? - Claudiu Constantin
1
因为在树形视图中,我需要实现禁用展开、设置选定项、禁用组的选择等逻辑。 - mathieu
1个回答

4
最终,我为设置组样式的选择器实现了一个空组 :
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。谢谢。 - Nelson Reis
1
将其声明为静态资源,并将其绑定到ListBox的GroupStyleSelector属性。将ListBox的ItemsSource属性绑定到CollectionViewSource。 - mathieu
感谢您的评论。您的答案与此其他答案 https://dev59.com/IkXRa4cB1Zd3GeqPs5Fo#226117 混合解决了我的问题。 - Nelson Reis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接