4

I am trying to make a custom groupstyle sector for my ListView as per other questions I've seen here on stack overflow.

public class TestGroupStyleSelector : GroupStyleSelector
{
    protected override GroupStyle SelectGroupStyleCore(object item, uint level)
    {
            return (GroupStyle)App.Current.Resources["grpStyle"];
    }
}

<ListView GroupStyleSelector="{StaticResource grpStyleSelector}">

I have two errors with this:

Error 1 'TestGroupStyleSelector': cannot derive from sealed type 'System.Windows.Controls.GroupStyleSelector'

Error 2 An object of the type "TestGroupStyleSelector" cannot be applied to a property that expects the type "System.Windows.Controls.GroupStyleSelector".

I have declared the class as other questions on here have shown, I am pretty lost at this point as to how to create a groupstyleselector for my listview, any ideas?

nextint
  • 81
  • 2
  • 6

2 Answers2

3

In WPF, using

<ListView GroupStyleSelector="{StaticResource grpStyleSelector}" />

and inheriting your selector from GroupStyleSelector will result in a 'cannot derive from sealed type 'System.Windows.Controls.GroupStyleSelector' exception.

Instead, use

<ListView>
   <ListView.GroupStyle>
     <GroupStyle ContainerStyleSelector="{StaticResource grpStyleSelector}"  />
   </ListView.GroupStyle>
</ListView>

and inherit your selector from StyleSelector

Nick
  • 790
  • 1
  • 8
  • 17
2

GroupStyleSelector is a Delegate exposed by ItemsControl:

Usage:

public GroupStyleSelector GroupStyleSelector
{
    get => (GroupStyleSelector)GetValue(GroupStyleSelectorProperty);
    set => SetValue(GroupStyleSelectorProperty, value);
}

Declaration:

public delegate GroupStyle GroupStyleSelector(CollectionViewGroup group, int level);

It is of type delegate which can't be inherited from as per the language specifications.

What you need to do is create a class deriving from StyleSelector:

public class GroupStyleSelector : StyleSelector
{
    public override Style SelectStyle(object item, DependencyObject container)
    {   
        return base.SelectStyle(item, container);
    }
}
g t
  • 7,287
  • 7
  • 50
  • 85
eran otzap
  • 12,293
  • 20
  • 84
  • 139