5

I can't make the {Binding Title} in the HeaderTemplate appear.

This is the class connected to the BindingContext:

class SensorGroup
{
    public string Title { get; set; }
    public IList<Sensor> Sensors { get; set; }
}

XAML:

<ListView  Header=""
           ItemsSource="{Binding Sensors}">

  <ListView.HeaderTemplate>
    <DataTemplate>
      <Grid>
        <Label Text="{Binding Title}"/>
      </Grid>
    </DataTemplate>
  </ListView.HeaderTemplate>

  <ListView.ItemTemplate>
  ...
</ListView>

If I replace it with <Label Text="Some static text"/>, the text appears.

I have found this related question, which links to this other question. But I could not make it work. I tried:

<ContentPage.Resources>
    <Label x:Key="MyTitle"
            Binding="{Title}"/>
</ContentPage.Resources>

...

<Grid>
    <StaticResource ResourceKey="MyTitle"/>
</Grid>

It gives me an error saying that the binding with Title cannot be found.

Community
  • 1
  • 1
Xavier Peña
  • 7,399
  • 9
  • 57
  • 99
  • Have you set up the DataContext correctly so that it can find the `SensorGroup` class? – ChrisF Jun 28 '16 at 21:50
  • The items of the `ListView ` which are binded to the property `Sensors` are being displayed correctly, so the `BindingContext = new SensorGroup()` (oversimplifying) written in the constructor is working properly. – Xavier Peña Jun 28 '16 at 21:54

1 Answers1

6

Sounds you like just need to do:

<ListView  Header="{Binding .}"
           ItemsSource="{Binding Sensors}">

That is if your ContentPage's BindingContext is set to the SensorGroup class.

The above is telling the ListView.Header to be bound to what ever the ContentPage.BindingContext is set to. That means that the ListView.HeaderTemplate controls will also use what ever ContentPage.BindingContext is set to.

Let me know if that does not make any sense.

hvaughan3
  • 10,955
  • 5
  • 56
  • 76
  • That was it. Thank you so much. It seems logical in hindsight, but I think I could have been staring at the code for weeks and I still wouldn't have figured it out by myself... I was following the Xamarin tutorials and they were telling me to set `Header=""` to make the header work (with static text, of course). So stupidly enough, I was following this rule blindly. – Xavier Peña Jun 28 '16 at 22:02
  • @XavierPeña Happy to help and I did the exact same thing until I finally found someone else's post on it. No point in losing hair without a good reason ;) – hvaughan3 Jun 28 '16 at 22:46
  • Thanks! Solved my problem :) shame Xamarin don't document it really! – Rexxo Nov 14 '16 at 17:13