简体   繁体   中英

XAML ListView: header binding not working

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM