mathieu
mathieu

Reputation: 31202

WPF Listbox grouping, items with no groups

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

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.

Upvotes: 6

Views: 2512

Answers (1)

mathieu
mathieu

Reputation: 31202

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>

Upvotes: 4

Related Questions