working with the ListView.GroupHeaderTemplate

One of my current projects makes used of ListView Grouping and for quite some period of time, I could not understand why my custom header template was not working, when code from other people’s projects that I had seen worked just fine.

So yesterday, I decided I had had enough and spent a couple of hours working section by section, line by line, to break an working sample then fix it again.  I learned something very important in the process.

A Working Sample

I started off with @JamesMontemagno’s Enhancing Xamarin.Forms ListView with Grouping Headers and customized it to make it look and function exactly as my project was designed.

Locating the Issue

The problem actually came down to these two properties:

 list.GroupDisplayBinding = new Binding("Key");
 list.GroupHeaderTemplate = new DataTemplate(typeof (HeaderCell));

Which the documentation clearly states as:

GroupHeaderTemplate is mutually exclusive with ListView.GroupDisplayBinding. Setting this property will set ListView.GroupDisplayBinding to null.

Which works exactly as it says it does.

The problem is with this code:

 list.GroupHeaderTemplate = new DataTemplate(typeof (HeaderCell));
 list.GroupDisplayBinding = new Binding("Key");

Again, the documentation clearly states:

This property is mutually exclusive with ListView.GroupHeaderTemplate property. Setting it will set ListView.GroupHeaderTemplate to null.

I didn’t happen to see that comment. Either that, or the documentation was updated later with that information and I never saw it.

The Solution

So the easiest solution to this issue is to not set the GroupDisplayBinding property. In all probability, your header template looks something like this:

  public class HeaderCell : ViewCell
  {
    public HeaderCell()
    {
      Height = 25;

      var title = new Label
      {
        FontSize = Device.GetNamedSize(NamedSize.Small, this),
        FontAttributes = FontAttributes.Bold,
        TextColor = Color.White,
        VerticalOptions = LayoutOptions.Center
      };

      title.SetBinding(Label.TextProperty, "Key");

      View = new StackLayout
      {
        HorizontalOptions = LayoutOptions.FillAndExpand,
        HeightRequest = 25,
        BackgroundColor = Color.FromRgb(52, 152, 218),
        Padding = 5,
        Orientation = StackOrientation.Horizontal,
        Children = { title }
      };
    }
  }

So you have already got your binding within the template, so it is not necessary to set the GroupDisplayBinding property.

 

Lessons Learned

And yes, you can probably guess where this is headed:  Read the damn manual!

Comments are closed