Apqu
Apqu

Reputation: 5031

Adding controls with bindings to an Xamarin ListView at runtime?

I am attempting to add a label with binding to a ListView at runtime (basic example for StackOverflow purposes, this isn't something I can just add to the XAML ItemTemplate).

The issue I am running into is that if I add a label with a binding as so:

private void Cell_OnAppearing(object sender, EventArgs e)
{
     View view = ((ViewCell) sender).View;
     StackLayout myStackLayout= (StackLayout)view.FindByName("myStackLayout");
     Label lblTest = new Label()
     {
          HorizontalOptions = LayoutOptions.StartAndExpand,
          VerticalOptions = LayoutOptions.Center,
          Text = "{Binding TestLabelText}"
     };
     myStackLayout.Children.Add(lblTest);
}

Rather than display the result of the binding the label just displays the text "{Binding TestLabelText}".

Is there a way to get this to work or alternatively to access the bound data for this ListView cell and set the Label text that way?

Upvotes: 0

Views: 309

Answers (1)

TheGeneral
TheGeneral

Reputation: 81493

You need to use SetBinding and potentially set the context

  • The BindingContext property specifies the source object.
  • The SetBinding method specifies the target property and source property.

Example

label.SetBinding(Label.TextProperty, "TestLabelText");

Another alternative, is just xaml the label at design time (where it can be precompiled), and change its visibility when needed.

Note : you need to be careful when changing the visual tree of a list item, there is a lot of caching and optimization done, changing the its size might cause you a problem

Upvotes: 1

Related Questions