Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Listbox grouping, items with no groups

Tags:

wpf

Is it possible to have a listbox (or another control that has a SelectedItem) bound to a ICollectionView, displaying items like this :

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

The class used as a source for the CollectionViewSource's view :

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

Item1 and Item2 have ParentName property set to null, Item3 and Item4 have "ParentName1" as ParentName property, and so on.

I really like the listbox approach because only items can be selected, groups are not selectable. But I may be going the wrong path.

like image 938
mathieu Avatar asked Oct 24 '11 15:10

mathieu


1 Answers

Finally I implemented a style selector for setting group style if group is null :

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;
    }
}

and group styles with templates :

<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>
like image 50
mathieu Avatar answered Nov 15 '22 04:11

mathieu