Reputation: 25
so I get a problem a binding item to listview
Initialization page
public HomePage()
{
Acquaintances = Add();
//InitializeToolbar();
InitializeComponent();
}
private ObservableCollection<Acquaintance> Add()
{
return new ObservableCollection<Acquaintance>()
{
new Acquaintance(){.....}
On XAML
<ListView x:Name="lstUser" BackgroundColor="White" ItemsSource="{Binding Acquaintances}">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
<ImageCell ImageSource="{Binding PhotoUrl}" Height="50"></ImageCell>
</Grid>
<StackLayout Grid.Column="1" Padding="5">
<Label Text="{Binding FirstName}" FontSize="15" TextColor="Black"></Label>
<Label Text="{Binding City}" FontSize="10" TextColor="Black"></Label>
<Label Text="{Binding JobTitle}" FontSize="10" TextColor="#CCCCCC"></Label>
</StackLayout>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
ListView can't be binding Acquaintances to items source of ListView. Where is wrong???
In Page:
public ObservableCollection<Acquaintance> Acquaintances { get; }
Upvotes: 1
Views: 2912
Reputation: 34128
It seems you are forgetting to set the BindingContext
property on your page. Without setting that property, the page does not know where to get data from.
To set your context to itself, do it like this:
public HomePage()
{
Acquaintances = Add();
//InitializeToolbar();
InitializeComponent();
BindingContext = this; // Note that I added this line
}
In the comments you are asking why it fails when you set BindingContext = Acquaintances;
and why it works when you set BindingContext = this;
.
It is simple, set the BindingContext
to the object holding properties that you want to access. By setting the context to this
, which is in this case HomePage
, you can use bindings such as {Binding Acquaintances}
. Because Acquaintances
is a property of HomePage
.
If you set the BindingContext
to a specific property, which can also be a complex type but doesn't have to be, you change the scope. So when you set the BindingContext
to Acquaintances
, you will have to change the ItemsSource
on your list to {Binding .}
. The dot means that it will use the object in the BindingContext
itself, not a property that is in it.
Upvotes: 2